├── app
├── .gitignore
├── src
│ └── main
│ │ ├── assets
│ │ └── xposed_init
│ │ ├── res
│ │ ├── mipmap
│ │ │ └── ic_launcher.png
│ │ ├── xml
│ │ │ └── network_config.xml
│ │ ├── values
│ │ │ ├── xposeds.xml
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── themes.xml
│ │ ├── drawable
│ │ │ ├── baseline_add_32.xml
│ │ │ ├── baseline_error_24.xml
│ │ │ ├── baseline_check_circle_24.xml
│ │ │ ├── baseline_search_24.xml
│ │ │ ├── baseline_save_24.xml
│ │ │ ├── baseline_about_us.xml
│ │ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ │ ├── activity_select_app.xml
│ │ │ ├── popup_action.xml
│ │ │ ├── rv_item_config.xml
│ │ │ ├── rv_item_app_select.xml
│ │ │ ├── dialog_about_me.xml
│ │ │ ├── activity_main.xml
│ │ │ └── activity_edit_config.xml
│ │ └── menu
│ │ │ └── menu_search.xml
│ │ ├── java
│ │ └── com
│ │ │ └── xiaoer
│ │ │ └── watermark
│ │ │ ├── bean
│ │ │ ├── SPContact.java
│ │ │ ├── WaterMarkConfig.java
│ │ │ └── AppConfig.java
│ │ │ ├── util
│ │ │ ├── DensityUtils.java
│ │ │ ├── LogUtil.java
│ │ │ ├── OpeConfigFromFile.java
│ │ │ ├── NetWorkUtil.java
│ │ │ ├── OpeConfigFromSp.java
│ │ │ ├── ProcessUtil.java
│ │ │ └── FileUtils.java
│ │ │ ├── ui
│ │ │ ├── main
│ │ │ │ ├── ConfigViewHolder.java
│ │ │ │ ├── MainActivityHandler.java
│ │ │ │ ├── ConfigAdapter.java
│ │ │ │ └── MainActivity.java
│ │ │ ├── WaterMarkView.java
│ │ │ ├── edit
│ │ │ │ ├── SelectPackageViewHolder.java
│ │ │ │ ├── SelectPackageAdapter.java
│ │ │ │ ├── SelectPackageActivity.java
│ │ │ │ └── EditConfigActivity.java
│ │ │ ├── WatermarkDrawable.java
│ │ │ └── Watermark.java
│ │ │ └── hook
│ │ │ ├── ConfigHelper.java
│ │ │ ├── AddWaterMark.java
│ │ │ └── WaterMarkManager.java
│ │ └── AndroidManifest.xml
├── version.properties
├── proguard-rules.pro
└── build.gradle
├── sign
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── README.md
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/sign:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yy-ss7/WaterMark/HEAD/sign
--------------------------------------------------------------------------------
/app/src/main/assets/xposed_init:
--------------------------------------------------------------------------------
1 | com.xiaoer.watermark.hook.AddWaterMark
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "WaterMark"
2 | include ':app'
3 |
--------------------------------------------------------------------------------
/app/version.properties:
--------------------------------------------------------------------------------
1 | #Wed May 31 16:25:59 CST 2023
2 | versionCode=1169
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yy-ss7/WaterMark/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Yy-ss7/WaterMark/HEAD/app/src/main/res/mipmap/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/xml/network_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/xposeds.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - android
5 |
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Apr 17 15:48:59 CST 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | WaterMark
3 | 模块已经激活
4 | 模块未激活
5 | 模块启动成功
6 | 请检查你是否已经正确激活了模块
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WaterMark
2 |
3 | ## 使用方法
4 | 1.下载模块并在LSPosed中激活本模块 作用域需要勾选”系统框架“ 第一次激活需要重启一次手机
5 |
6 | 2.LSPosed中 模块作用域勾选要增加水印的app
7 |
8 | 3.进入模块 右下角增加配置 设置水印名称、大小、旋转角度、应用APP等信息
9 |
10 | 4.杀死目标应用进程,重新启动即可使用
11 |
12 | ## 注意
13 |
14 | LSposed和模块配置中都需要勾选要增加水印的app
15 |
16 | 比如想在微信上增加水印,lsposed中模块设置里勾选微信,模块里增加配置时在”生效应用“中也勾选微信
17 |
18 | ## issue
19 | 如果有问题,欢迎反馈!
20 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/baseline_add_32.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #F44336
6 | #FF3700B3
7 | #FF03DAC5
8 | #FF018786
9 | #FF000000
10 | #FFFFFFFF
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/bean/SPContact.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.bean;
2 |
3 | public class SPContact {
4 | public static final String WATER_MARK_CONFIG_FILE_NAME = "watermarkConfig";
5 | public static final String APP_CONFIG = "appConfig";
6 |
7 | public static final String DEBUGGABLE = "debuggable";
8 | public static final String WATER_MARK_CONFIG_KEY = "water_mark_config";
9 | public static final String IS_CAN_SHOW_LOG = "is_can_show_log";
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/baseline_error_24.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/baseline_check_circle_24.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/DensityUtils.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import android.content.Context;
4 |
5 | public class DensityUtils {
6 |
7 | public static int dip2px(Context context, float dipValue) {
8 | return Math.round(dipValue * (context.getResources().getDisplayMetrics().density));
9 | }
10 |
11 | public static int px2dip(Context context, float pxValue) {
12 | return Math.round(pxValue / (context.getResources().getDisplayMetrics().density));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_select_app.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/baseline_search_24.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_search.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/baseline_save_24.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/main/ConfigViewHolder.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.main;
2 |
3 | import android.view.View;
4 | import android.widget.TextView;
5 |
6 | import androidx.annotation.NonNull;
7 | import androidx.recyclerview.widget.RecyclerView;
8 |
9 | import com.google.android.material.card.MaterialCardView;
10 | import com.xiaoer.watermark.R;
11 |
12 | public class ConfigViewHolder extends RecyclerView.ViewHolder {
13 |
14 | public MaterialCardView mCardView;
15 | public TextView mTvContent;
16 |
17 | public ConfigViewHolder(@NonNull View itemView) {
18 | super(itemView);
19 | mCardView = itemView.findViewById(R.id.mcv_root);
20 | mTvContent = itemView.findViewById(R.id.tv_content);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/popup_action.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
14 |
15 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/baseline_about_us.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
12 |
15 |
16 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/main/MainActivityHandler.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.main;
2 |
3 | import android.os.Handler;
4 | import android.os.Message;
5 |
6 | import androidx.annotation.NonNull;
7 |
8 | import java.lang.ref.WeakReference;
9 |
10 | public class MainActivityHandler extends Handler {
11 |
12 | public static final int OK = -1;
13 | private final WeakReference mActivity;
14 |
15 | public MainActivityHandler(MainActivity activity) {
16 | mActivity = new WeakReference<>(activity);
17 | }
18 |
19 | @Override
20 | public void handleMessage(@NonNull Message msg) {
21 | if (msg.what == OK){
22 | MainActivity mainActivity = mActivity.get();
23 | if(mainActivity != null){
24 | mainActivity.getWindow().getDecorView().postDelayed(mainActivity::updateRecyclerView, 400);
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/rv_item_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
16 |
17 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/LogUtil.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import android.app.Application;
4 | import android.text.TextUtils;
5 | import android.util.Log;
6 |
7 | import com.xiaoer.watermark.BuildConfig;
8 | import com.xiaoer.watermark.hook.ConfigHelper;
9 |
10 | import de.robv.android.xposed.XposedBridge;
11 |
12 | public class LogUtil {
13 | private static Application mApplication;
14 | private LogUtil(){}
15 |
16 | public static void init(Application application){
17 | mApplication = application;
18 | }
19 | public static void d(String log) {
20 | print("yys " + log);
21 | }
22 |
23 | public static void e(String errorMsg) {
24 | print("yys error: " + errorMsg);
25 | }
26 |
27 | private static void print(String msg){
28 | if(canShowLog()){
29 | if(mApplication != null && TextUtils.equals(mApplication.getPackageName(), BuildConfig.APPLICATION_ID)){
30 | XposedBridge.log(msg);
31 | }else {
32 | Log.d("Xposed", msg);
33 | }
34 | }
35 | }
36 |
37 | private static boolean canShowLog(){
38 | return BuildConfig.DEBUG;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/WaterMarkView.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui;
2 |
3 | import android.content.Context;
4 | import android.util.AttributeSet;
5 | import android.view.ViewGroup;
6 | import android.widget.FrameLayout;
7 | import android.widget.ImageView;
8 |
9 |
10 | public class WaterMarkView extends ImageView {
11 | private WatermarkDrawable mWatermarkDrawable;
12 |
13 | public WaterMarkView(Context context) {
14 | super(context);
15 | init();
16 | }
17 |
18 | public WaterMarkView(Context context, WatermarkDrawable watermarkDrawable) {
19 | super(context);
20 | this.mWatermarkDrawable = watermarkDrawable;
21 | init();
22 | }
23 |
24 | public WaterMarkView(Context context, AttributeSet attrs) {
25 | this(context, attrs, 0);
26 | }
27 |
28 | public WaterMarkView(Context context, AttributeSet attrs, int defStyleAttr) {
29 | super(context, attrs, defStyleAttr);
30 | init();
31 | }
32 |
33 | private void init() {
34 | FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
35 | setLayoutParams(layoutParams);
36 | setBackground(mWatermarkDrawable);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/edit/SelectPackageViewHolder.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.edit;
2 |
3 | import android.view.View;
4 |
5 | import androidx.annotation.NonNull;
6 | import androidx.recyclerview.widget.RecyclerView;
7 |
8 | import com.google.android.material.card.MaterialCardView;
9 | import com.google.android.material.checkbox.MaterialCheckBox;
10 | import com.google.android.material.imageview.ShapeableImageView;
11 | import com.google.android.material.textview.MaterialTextView;
12 | import com.xiaoer.watermark.R;
13 |
14 | public class SelectPackageViewHolder extends RecyclerView.ViewHolder {
15 |
16 | public final MaterialCardView mMcvRoot;
17 | public final ShapeableImageView mIvAppIcon;
18 | public final MaterialTextView mTvPackageName;
19 | public final MaterialTextView mTvAppName;
20 | public final MaterialCheckBox mMcbCheck;
21 |
22 | public SelectPackageViewHolder(@NonNull View itemView) {
23 | super(itemView);
24 | mMcvRoot = itemView.findViewById(R.id.mcv_root);
25 | mIvAppIcon = mMcvRoot.findViewById(R.id.iv_appIcon);
26 | mTvAppName = mMcvRoot.findViewById(R.id.mtv_appName);
27 | mTvPackageName = mMcvRoot.findViewById(R.id.mtv_packageName);
28 | mMcbCheck = mMcvRoot.findViewById(R.id.mcb_check);
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Enables namespacing of each library's R class so that its R class includes only the
19 | # resources declared in the library itself and none from the library's dependencies,
20 | # thereby reducing the size of the R class for that library
21 | android.nonTransitiveRClass=true
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
10 |
11 |
18 |
21 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
37 |
40 |
43 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 |
7 | def packageNames = ['com.tencent.mm', 'com.jd.jxj', 'com.tencent.mobileqq']
8 |
9 | android {
10 | def realVersioncode = getVersionCode()
11 | compileSdkVersion 31
12 |
13 | defaultConfig {
14 | applicationId "com.xiaoer.watermark"
15 | minSdkVersion 28
16 | targetSdkVersion 31
17 | versionCode realVersioncode
18 | versionName "1.8"
19 | }
20 |
21 | buildTypes {
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility JavaVersion.VERSION_1_8
29 | targetCompatibility JavaVersion.VERSION_1_8
30 | }
31 | }
32 | //task(KillProcess) {
33 | // for (i in 0.. packageList = new ArrayList<>();
24 | public int getTextColor() {
25 | return textColor;
26 | }
27 |
28 | public void setTextColor(int textColor) {
29 | this.textColor = textColor;
30 | }
31 |
32 | public String getContent() {
33 | return content;
34 | }
35 |
36 | public void setContent(String content) {
37 | this.content = content;
38 | }
39 |
40 | public int getTextSize() {
41 | return textSize;
42 | }
43 |
44 | public void setTextSize(int textSize) {
45 | this.textSize = textSize;
46 | }
47 |
48 | public float getRotation() {
49 | return rotation;
50 | }
51 |
52 | public void setRotation(float rotation) {
53 | this.rotation = rotation;
54 | }
55 |
56 | public String getConfigId() {
57 | return configId;
58 | }
59 |
60 | public void setConfigId(String configId) {
61 | this.configId = configId;
62 | }
63 |
64 | public void setAppList(ArrayList newList) {
65 | if(newList == null){
66 | newList = new ArrayList<>();
67 | }
68 | packageList = newList;
69 | }
70 |
71 | public ArrayList getAppList(){
72 | return packageList;
73 | }
74 |
75 | @Override
76 | public String toString() {
77 | return "WaterMarkConfig{" + "content='" + content + '\'' + ", configId='" + configId + '\'' + ", packageList=" + packageList + '}';
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/bean/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.bean;
2 |
3 | import java.io.Serializable;
4 | import java.util.ArrayList;
5 | import java.util.Arrays;
6 |
7 | public class AppConfig implements Serializable {
8 | private int code;
9 | private Data data;
10 |
11 | public Data getData() {
12 | return data;
13 | }
14 |
15 | public void setData(Data data) {
16 | this.data = data;
17 | }
18 |
19 | public int getCode() {
20 | return code;
21 | }
22 |
23 | public void setCode(int code) {
24 | this.code = code;
25 | }
26 |
27 | public ArrayList getAppList() {
28 | return data.getAppList();
29 | }
30 |
31 | public void setAppList(ArrayList appList) {
32 | data.setAppList(appList);
33 | }
34 |
35 | @Override
36 | public String toString() {
37 | return "AppConfig{" + "code=" + code + ", mData=" + data + '}';
38 | }
39 |
40 | public static class AppBean {
41 | private String packageName;
42 | private String[] versionCode;
43 |
44 | public String getPackageName() {
45 | return packageName;
46 | }
47 |
48 | public void setPackageName(String packageName) {
49 | this.packageName = packageName;
50 | }
51 |
52 | public String[] getVersionCode() {
53 | return versionCode;
54 | }
55 |
56 | public void setVersionCode(String[] versionCode) {
57 | this.versionCode = versionCode;
58 | }
59 |
60 | @Override
61 | public String toString() {
62 | return "AppBean{" + "packageName='" + packageName + '\'' + ", versionCode=" + Arrays.toString(versionCode) + '}';
63 | }
64 | }
65 |
66 | public static class Data{
67 | private ArrayList appList;
68 |
69 | public ArrayList getAppList() {
70 | return appList;
71 | }
72 |
73 | public void setAppList(ArrayList appList) {
74 | this.appList = appList;
75 | }
76 |
77 | @Override
78 | public String toString() {
79 | return "Data{" + "appList=" + appList + '}';
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/rv_item_app_select.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
20 |
21 |
31 |
32 |
42 |
43 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/dialog_about_me.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
15 |
16 |
22 |
23 |
32 |
33 |
42 |
43 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/WatermarkDrawable.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui;
2 |
3 | import android.content.Context;
4 | import android.graphics.Canvas;
5 | import android.graphics.ColorFilter;
6 | import android.graphics.Paint;
7 | import android.graphics.PixelFormat;
8 | import android.graphics.drawable.Drawable;
9 |
10 | import com.xiaoer.watermark.bean.WaterMarkConfig;
11 | import com.xiaoer.watermark.util.DensityUtils;
12 |
13 | public class WatermarkDrawable extends Drawable {
14 | public final Paint mPaint;
15 | /**
16 | * 水印文本
17 | */
18 | public String mText;
19 | /**
20 | * 字体颜色,十六进制形式,例如:0xAEAEAEAE
21 | */
22 | public int mTextColor = 0xAEAEAEAE;
23 | /**
24 | * 字体大小,单位为sp
25 | */
26 | public float mTextSize;
27 | /**
28 | * 旋转角度
29 | */
30 | public float mRotation;
31 |
32 | private final Context mContext;
33 |
34 | public WatermarkDrawable(Context context) {
35 | this.mPaint = new Paint();
36 | this.mContext = context;
37 | }
38 |
39 | public WatermarkDrawable(Context context, WaterMarkConfig waterMarkConfig) {
40 | this.mPaint = new Paint();
41 | this.mContext = context;
42 | this.mText = waterMarkConfig.getContent();
43 | this.mTextColor = waterMarkConfig.getTextColor();
44 | this.mTextSize = waterMarkConfig.getTextSize();
45 | this.mRotation = waterMarkConfig.getRotation();
46 | }
47 |
48 | @Override
49 | public void draw(Canvas canvas) {
50 | int width = getBounds().right;
51 | int height = getBounds().bottom;
52 | int diagonal = (int) Math.sqrt(width * width + height * height); // 对角线的长度
53 |
54 | mPaint.setColor(mTextColor);
55 | mPaint.setTextSize(DensityUtils.dip2px(mContext, mTextSize));
56 | mPaint.setAntiAlias(true);
57 | float textWidth = mPaint.measureText(mText);
58 |
59 | canvas.drawColor(0x00000000);
60 | // 将canvas的坐标系平移到中心点
61 | canvas.translate(width / 2f, height / 2f);
62 | // 进行旋转
63 | canvas.rotate(mRotation);
64 | // 将canvas的坐标系平移回原来的位置
65 | canvas.translate(-width / 2f, -height / 2f);
66 |
67 | int index = 0;
68 | float fromX;
69 | // 以对角线的长度来做高度,这样可以保证竖屏和横屏整个屏幕都能布满水印
70 | for (int positionY = diagonal / 10; positionY <= diagonal; positionY += diagonal / 10) {
71 | fromX = -width + (index++ % 2) * textWidth; // 上下两行的X轴起始点不一样,错开显示
72 | for (float positionX = fromX; positionX < width; positionX += textWidth * 2) {
73 | canvas.drawText(mText, positionX, positionY, mPaint);
74 | }
75 | }
76 |
77 | canvas.save();
78 | canvas.restore();
79 | }
80 |
81 | @Override
82 | public void setAlpha(int alpha) {
83 | }
84 |
85 | @Override
86 | public void setColorFilter(ColorFilter colorFilter) {
87 | }
88 |
89 | @Override
90 | public int getOpacity() {
91 | return PixelFormat.TRANSLUCENT;
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/hook/ConfigHelper.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.hook;
2 |
3 | import android.content.Context;
4 | import android.widget.Toast;
5 |
6 | import com.xiaoer.watermark.BuildConfig;
7 | import com.xiaoer.watermark.bean.AppConfig;
8 | import com.xiaoer.watermark.bean.WaterMarkConfig;
9 | import com.xiaoer.watermark.util.OpeConfigFromFile;
10 | import com.xiaoer.watermark.util.OpeConfigFromSp;
11 |
12 | import java.util.List;
13 |
14 | public class ConfigHelper {
15 |
16 | public static boolean canUseSp = false;
17 |
18 | public static boolean canUseSp(){
19 | return false;
20 | }
21 |
22 | public static List getWaterMarkConfigs(Context context) {
23 | if(canUseSp()){
24 | return OpeConfigFromSp.getInstance().getWaterMarkConfigs(context);
25 | }else {
26 | return OpeConfigFromFile.getWaterMarkConfigs(context);
27 | }
28 | }
29 |
30 | public static WaterMarkConfig getCurrentAppConfig(Context context) {
31 | if(canUseSp()){
32 | return OpeConfigFromSp.getInstance().getCurrentAppConfig(context);
33 | }else {
34 | return OpeConfigFromFile.getCurrentAppConfig(context);
35 | }
36 | }
37 |
38 | public static boolean saveWaterMarkConfig(Context context, WaterMarkConfig config){
39 | if(canUseSp()){
40 | OpeConfigFromSp.getInstance().saveWaterMarkConfig(context, config);
41 | return true;
42 | }else {
43 | boolean success = OpeConfigFromFile.saveWaterMarkConfig(context, config);
44 | if(success){
45 | Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
46 | }else {
47 | Toast.makeText(context,"保存失败",Toast.LENGTH_SHORT).show();
48 | }
49 | return success;
50 | }
51 | }
52 |
53 | public static boolean deleteWaterMarkConfig(Context context, WaterMarkConfig config){
54 | if(canUseSp()){
55 | OpeConfigFromSp.getInstance().deleteWaterMarkConfig(context, config);
56 | return true;
57 | }else {
58 | boolean success = OpeConfigFromFile.deleteWaterMarkConfig(context, config);
59 | if(success){
60 | Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
61 | }else {
62 | Toast.makeText(context,"删除失败",Toast.LENGTH_SHORT).show();
63 | }
64 | return success;
65 | }
66 | }
67 |
68 | public static boolean saveAppConfig(Context context, AppConfig config) {
69 | if(canUseSp()){
70 | OpeConfigFromSp.getInstance().saveAppConfig(context, config);
71 | return true;
72 | }else {
73 | return OpeConfigFromFile.saveAppConfig(context, config);
74 | }
75 | }
76 |
77 | public static AppConfig getAppConfig(Context context){
78 | if(canUseSp()){
79 | return OpeConfigFromSp.getInstance().getAppConfig(context);
80 | }else {
81 | return OpeConfigFromFile.getAppConfig(context);
82 | }
83 | }
84 |
85 | public static boolean isModuleActivated() {
86 | return false;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/Watermark.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui;
2 |
3 | import android.app.Activity;
4 | import android.view.ViewGroup;
5 | import android.view.ViewTreeObserver;
6 |
7 | import java.lang.ref.SoftReference;
8 |
9 | public class Watermark {
10 | /**
11 | * 水印文本
12 | */
13 | private String mText;
14 | /**
15 | * 字体颜色,十六进制形式,例如:0xAEAEAEAE
16 | */
17 | private int mTextColor;
18 | /**
19 | * 字体大小,单位为sp
20 | */
21 | private float mTextSize;
22 | /**
23 | * 旋转角度
24 | */
25 | private float mRotation;
26 |
27 | private final SoftReference mActivitySoftReference;
28 | private WaterMarkView mWaterMarkView;
29 |
30 | public Watermark(Activity activity) {
31 | this.mActivitySoftReference = new SoftReference<>(activity);
32 | ViewGroup rootView = getActivityRootView();
33 | if(rootView == null){
34 | return;
35 | }
36 | ViewTreeObserver viewTreeObserver = rootView.getViewTreeObserver();
37 | viewTreeObserver.addOnGlobalFocusChangeListener((oldFocus, newFocus) -> {
38 | if(!(newFocus instanceof WaterMarkView)){
39 | show(mText);
40 | }
41 | });
42 | }
43 |
44 |
45 | /**
46 | * 设置水印文本
47 | *
48 | * @param text 文本
49 | * @return Watermark实例
50 | */
51 | public void setText(String text) {
52 | mText = text;
53 | }
54 |
55 | /**
56 | * 设置字体颜色
57 | *
58 | * @param color 颜色,十六进制形式,例如:0xAEAEAEAE
59 | */
60 | public void setTextColor(int color) {
61 | mTextColor = color;
62 | }
63 |
64 | /**
65 | * 设置字体大小
66 | *
67 | * @param size 大小,单位为sp
68 | */
69 | public void setTextSize(float size) {
70 | mTextSize = size;
71 | }
72 |
73 | /**
74 | * 设置旋转角度
75 | *
76 | * @param degrees 度数
77 | */
78 | public void setRotation(float degrees) {
79 | mRotation = degrees;
80 | }
81 |
82 | /**
83 | * 显示水印,铺满整个页面
84 | *
85 | */
86 | public void show() {
87 | show(mText);
88 | }
89 |
90 | /**
91 | * 显示水印,铺满整个页面
92 | *
93 | * @param text 水印
94 | */
95 | public void show(String text) {
96 | removeIfExit();
97 | addIntoRootView(text);
98 | }
99 |
100 | private void addIntoRootView(String text){
101 | ViewGroup rootView = getActivityRootView();
102 | if(rootView == null){
103 | return;
104 | }
105 | WatermarkDrawable drawable = new WatermarkDrawable(rootView.getContext());
106 | drawable.mText = text;
107 | drawable.mTextColor = mTextColor;
108 | drawable.mTextSize = mTextSize;
109 | drawable.mRotation = mRotation;
110 | mWaterMarkView = new WaterMarkView(rootView.getContext(), drawable);
111 | rootView.post(() -> {
112 | if (mWaterMarkView.getParent() == null) {
113 | rootView.addView(mWaterMarkView, -1);
114 | }
115 | });
116 | }
117 |
118 | private ViewGroup getActivityRootView(){
119 | if(mActivitySoftReference == null || mActivitySoftReference.get() == null){
120 | return null;
121 | }
122 | return (ViewGroup) mActivitySoftReference.get().getWindow().getDecorView();
123 | }
124 |
125 | private void removeIfExit(){
126 | if(mWaterMarkView == null){
127 | return;
128 | }
129 | ViewGroup activityRootView = getActivityRootView();
130 | if(activityRootView != null){
131 | activityRootView.removeView(mWaterMarkView);
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/OpeConfigFromFile.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import static com.xiaoer.watermark.bean.SPContact.APP_CONFIG;
4 | import static com.xiaoer.watermark.bean.SPContact.DEBUGGABLE;
5 |
6 | import android.content.Context;
7 | import android.text.TextUtils;
8 |
9 | import com.google.gson.Gson;
10 | import com.google.gson.reflect.TypeToken;
11 | import com.xiaoer.watermark.bean.AppConfig;
12 | import com.xiaoer.watermark.bean.SPContact;
13 | import com.xiaoer.watermark.bean.WaterMarkConfig;
14 |
15 | import java.util.ArrayList;
16 | import java.util.List;
17 |
18 | public class OpeConfigFromFile {
19 |
20 | public static boolean saveAppConfig(Context context, AppConfig config) {
21 | LogUtil.d("OpeConfigFromFile saveAppConfig:" + config);
22 | return FileUtils.getInstance().saveFile(context, APP_CONFIG, new Gson().toJson(config));
23 | }
24 |
25 | public static AppConfig getAppConfig(Context context){
26 | AppConfig appConfig = new Gson().fromJson(FileUtils.getInstance().readFile(context, APP_CONFIG), AppConfig.class);
27 | LogUtil.d("OpeConfigFromFile cache appConfig: " + (appConfig == null ? "null" : appConfig));
28 | return appConfig;
29 | }
30 |
31 | public static boolean saveWaterMarkConfig(Context context, WaterMarkConfig config) {
32 | List waterMarkConfigs = getWaterMarkConfigs(context);
33 | List result = new ArrayList<>();
34 | Gson gson = new Gson();
35 | if(waterMarkConfigs.size() == 0){
36 | result.add(config);
37 | }else {
38 | boolean hasAdd = false;
39 | for (WaterMarkConfig waterMarkConfig : waterMarkConfigs) {
40 | if (!TextUtils.equals(waterMarkConfig.configId, config.configId)) {
41 | result.add(waterMarkConfig);
42 | }else {
43 | hasAdd = true;
44 | result.add(config);
45 | }
46 | }
47 | if(!hasAdd){
48 | result.add(config);
49 | }
50 | }
51 | return FileUtils.getInstance().saveFile(context, SPContact.WATER_MARK_CONFIG_FILE_NAME, gson.toJson(result));
52 | }
53 |
54 | public static boolean deleteWaterMarkConfig(Context context, WaterMarkConfig config) {
55 | List waterMarkConfigs = getWaterMarkConfigs(context);
56 | List result = new ArrayList<>();
57 | Gson gson = new Gson();
58 | for (WaterMarkConfig waterMarkConfig : waterMarkConfigs) {
59 | if (!TextUtils.equals(waterMarkConfig.configId, config.configId)) {
60 | result.add(waterMarkConfig);
61 | }
62 | }
63 | if(result.size() == 0){
64 | return FileUtils.getInstance().deleteFile(context, SPContact.WATER_MARK_CONFIG_FILE_NAME);
65 | }else {
66 | return FileUtils.getInstance().saveFile(context, SPContact.WATER_MARK_CONFIG_FILE_NAME, gson.toJson(result));
67 | }
68 | }
69 |
70 |
71 | public static List getWaterMarkConfigs(Context context) {
72 | String json = FileUtils.getInstance().readFile(context, SPContact.WATER_MARK_CONFIG_FILE_NAME);
73 | ArrayList result = new Gson().fromJson(json, new TypeToken>() {});
74 | return result == null ? new ArrayList<>() : result;
75 | }
76 |
77 | public static WaterMarkConfig getCurrentAppConfig(Context context) {
78 | List waterMarkConfigs = getWaterMarkConfigs(context);
79 | for (WaterMarkConfig item : waterMarkConfigs) {
80 | if (item.isOpen() && item.packageList != null && item.packageList.contains(context.getPackageName())) {
81 | return item;
82 | }
83 | }
84 | return null;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
22 |
23 |
27 |
28 |
35 |
36 |
41 |
42 |
49 |
50 |
57 |
58 |
66 |
67 |
68 |
69 |
70 |
71 |
75 |
76 |
80 |
81 |
82 |
83 |
92 |
93 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_edit_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
18 |
19 |
29 |
30 |
36 |
37 |
38 |
44 |
45 |
49 |
50 |
56 |
57 |
61 |
62 |
63 |
64 |
71 |
72 |
77 |
78 |
85 |
86 |
91 |
92 |
99 |
100 |
107 |
108 |
109 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/hook/AddWaterMark.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.hook;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.os.Bundle;
6 |
7 | import com.github.kyuubiran.ezxhelper.EzXHelper;
8 | import com.github.kyuubiran.ezxhelper.HookFactory;
9 | import com.github.kyuubiran.ezxhelper.finders.MethodFinder;
10 | import com.xiaoer.watermark.BuildConfig;
11 | import com.xiaoer.watermark.util.FileUtils;
12 | import com.xiaoer.watermark.util.LogUtil;
13 | import com.xiaoer.watermark.util.ProcessUtil;
14 |
15 | import java.lang.reflect.Method;
16 |
17 | import de.robv.android.xposed.IXposedHookLoadPackage;
18 | import de.robv.android.xposed.IXposedHookZygoteInit;
19 | import de.robv.android.xposed.XC_MethodHook;
20 | import de.robv.android.xposed.XposedBridge;
21 | import de.robv.android.xposed.XposedHelpers;
22 | import de.robv.android.xposed.callbacks.XC_LoadPackage;
23 |
24 |
25 | public class AddWaterMark implements IXposedHookLoadPackage, IXposedHookZygoteInit {
26 | private static Application mApplication;
27 |
28 | @Override
29 | public void initZygote(StartupParam startupParam) {
30 | EzXHelper.initZygote(startupParam);
31 | FileUtils.getInstance().initZygote();
32 | }
33 | @Override
34 | public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws ClassNotFoundException {
35 | if (lpparam != null){
36 | if (lpparam.packageName.equals("android")) {
37 | LogUtil.d("hook android XposedBridge.getXposedVersion(): " + XposedBridge.getXposedVersion());
38 | EzXHelper.initHandleLoadPackage(lpparam);
39 | FileUtils.getInstance().hookAMS(lpparam);
40 | }
41 |
42 | XposedHelpers.findAndHookMethod("android.app.Application", lpparam.classLoader, "onCreate", new XC_MethodHook() {
43 | @Override
44 | protected void afterHookedMethod(MethodHookParam param) throws Throwable {
45 | super.afterHookedMethod(param);
46 | mApplication = (Application) param.thisObject;
47 | if(lpparam.packageName.equals(BuildConfig.APPLICATION_ID)){
48 | Class> loadClass = lpparam.classLoader.loadClass("com.xiaoer.watermark.hook.ConfigHelper");
49 | Method isModuleActivated = MethodFinder.fromClass(loadClass).filterByName("isModuleActivated").first();
50 | HookFactory.createMethodHook(isModuleActivated, hookFactory -> hookFactory.before(methodHookParam -> methodHookParam.setResult(true)));
51 | }
52 |
53 | if (ProcessUtil.isMainProcess()) {
54 | LogUtil.init(mApplication);
55 | if(!lpparam.packageName.equals(BuildConfig.APPLICATION_ID)) {
56 | WaterMarkManager.init(mApplication);
57 | }
58 | addListener(mApplication);
59 | }
60 | }
61 | });
62 | }
63 | }
64 |
65 | public static void addListener(Application application){
66 | application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
67 | @Override
68 | public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
69 | WaterMarkManager.getInstance().addWaterMark(activity);
70 | }
71 |
72 | @Override
73 | public void onActivityStarted(Activity activity) {
74 |
75 | }
76 |
77 | @Override
78 | public void onActivityResumed(Activity activity) {
79 | }
80 |
81 | @Override
82 | public void onActivityPaused(Activity activity) {
83 |
84 | }
85 |
86 | @Override
87 | public void onActivityStopped(Activity activity) {
88 |
89 | }
90 |
91 | @Override
92 | public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
93 |
94 | }
95 |
96 | @Override
97 | public void onActivityDestroyed(Activity activity) {
98 | WaterMarkManager.getInstance().removeWaterMark(activity);
99 | }
100 | });
101 | }
102 |
103 | public static Application getApplication(){
104 | return mApplication;
105 | }
106 |
107 | }
108 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/edit/SelectPackageAdapter.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.edit;
2 |
3 | import android.content.Context;
4 | import android.content.pm.PackageInfo;
5 | import android.text.TextUtils;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 | import android.webkit.ValueCallback;
10 |
11 | import androidx.annotation.NonNull;
12 | import androidx.recyclerview.widget.RecyclerView;
13 |
14 | import com.xiaoer.watermark.R;
15 |
16 | import java.util.ArrayList;
17 | import java.util.concurrent.CopyOnWriteArrayList;
18 |
19 | public class SelectPackageAdapter extends RecyclerView.Adapter {
20 |
21 | private final CopyOnWriteArrayList mAllPackages;
22 |
23 | private CopyOnWriteArrayList mShowPackages;
24 | private final CopyOnWriteArrayList mSelectList;
25 | private final Context mContext;
26 |
27 | public SelectPackageAdapter(Context context, ArrayList packageInfoList, ArrayList selectList) {
28 | mContext = context;
29 | mSelectList = new CopyOnWriteArrayList<>(selectList);
30 | mAllPackages = new CopyOnWriteArrayList<>(packageInfoList);
31 | mShowPackages = new CopyOnWriteArrayList<>(packageInfoList);
32 | updateSelectList(null);
33 | }
34 |
35 | public void updateSelectList(ValueCallback callback) {
36 | new Thread(() -> {
37 | ArrayList result = new ArrayList<>();
38 | int preCheckIndex = 0;
39 | for (PackageInfo item: mAllPackages){
40 | if(mSelectList.contains(item.packageName)){
41 | result.add(preCheckIndex++ , item);
42 | }else {
43 | result.add(item);
44 | }
45 | }
46 | mShowPackages = new CopyOnWriteArrayList<>(result);
47 | if (callback != null){
48 | callback.onReceiveValue(true);
49 | }
50 | }).start();
51 | }
52 |
53 | public void filterPackage(String filter, ValueCallback callback){
54 | new Thread(() -> {
55 | if (TextUtils.isEmpty(filter)) {
56 | updateSelectList(null);
57 | } else {
58 | mShowPackages = new CopyOnWriteArrayList<>();
59 | for (PackageInfo packageInfo : mAllPackages) {
60 | if (packageInfo.applicationInfo.loadLabel(mContext.getPackageManager()).toString().contains(filter)) {
61 | mShowPackages.add(packageInfo);
62 | }
63 | }
64 | }
65 | if (callback != null) {
66 | callback.onReceiveValue(true);
67 | }
68 | }).start();
69 | }
70 |
71 | public ArrayList getSelectAppList(){
72 | return new ArrayList<>(mSelectList);
73 | }
74 |
75 | @NonNull
76 | @Override
77 | public SelectPackageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
78 | View view = LayoutInflater.from(mContext).inflate(R.layout.rv_item_app_select, parent, false);
79 | return new SelectPackageViewHolder(view);
80 | }
81 |
82 | @Override
83 | public void onBindViewHolder(@NonNull SelectPackageViewHolder holder, int position) {
84 | PackageInfo packageInfo = mShowPackages.get(position);
85 | holder.mMcvRoot.setOnClickListener(v -> holder.mMcbCheck.setChecked(!holder.mMcbCheck.isChecked()));
86 | holder.mMcbCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
87 | if (isChecked){
88 | if (!mSelectList.contains(packageInfo.packageName)) {
89 | mSelectList.add(packageInfo.packageName);
90 | }
91 | }else {
92 | mSelectList.remove(packageInfo.packageName);
93 | }
94 | });
95 | holder.mMcbCheck.setChecked(mSelectList.contains(packageInfo.packageName));
96 | holder.mTvAppName.setText(packageInfo.applicationInfo.loadLabel(mContext.getPackageManager()));
97 | holder.mIvAppIcon.setImageDrawable(packageInfo.applicationInfo.loadIcon(mContext.getPackageManager()));
98 | holder.mTvPackageName.setText(packageInfo.packageName);
99 |
100 | }
101 |
102 | @Override
103 | public int getItemCount() {
104 | return mShowPackages.size();
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/main/ConfigAdapter.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.main;
2 |
3 | import static com.xiaoer.watermark.hook.ConfigHelper.isModuleActivated;
4 |
5 | import android.annotation.SuppressLint;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.graphics.Point;
9 | import android.util.Log;
10 | import android.view.Gravity;
11 | import android.view.LayoutInflater;
12 | import android.view.MotionEvent;
13 | import android.view.View;
14 | import android.view.ViewGroup;
15 | import android.widget.Button;
16 | import android.widget.PopupWindow;
17 |
18 | import androidx.activity.result.ActivityResultLauncher;
19 | import androidx.annotation.NonNull;
20 | import androidx.recyclerview.widget.RecyclerView;
21 |
22 | import com.xiaoer.watermark.R;
23 | import com.xiaoer.watermark.bean.WaterMarkConfig;
24 | import com.xiaoer.watermark.hook.ConfigHelper;
25 | import com.xiaoer.watermark.ui.edit.EditConfigActivity;
26 | import com.xiaoer.watermark.util.DensityUtils;
27 |
28 | import java.util.List;
29 |
30 | public class ConfigAdapter extends RecyclerView.Adapter{
31 | private List mWaterMarkConfigs;
32 | private final ActivityResultLauncher mResultLauncher;
33 | private final Context mContext;
34 |
35 | private Point lastTouchPosition = new Point(0, 0);
36 |
37 | public ConfigAdapter(Context context, List waterMarkConfigs, ActivityResultLauncher resultLauncher){
38 | this.mContext = context;
39 | this.mWaterMarkConfigs = waterMarkConfigs;
40 | this.mResultLauncher = resultLauncher;
41 | }
42 |
43 | public void setWaterMarkConfigs(List waterMarkConfigs){
44 | this.mWaterMarkConfigs = waterMarkConfigs;
45 | }
46 |
47 | @NonNull
48 | @Override
49 | public ConfigViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
50 | View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item_config, parent, false);
51 | return new ConfigViewHolder(inflate);
52 | }
53 |
54 | @SuppressLint("ClickableViewAccessibility")
55 | @Override
56 | public void onBindViewHolder(@NonNull ConfigViewHolder holder, int position) {
57 | WaterMarkConfig waterMarkConfig = mWaterMarkConfigs.get(position);
58 | if (waterMarkConfig.isOpen() && isModuleActivated()){
59 | holder.itemView.setAlpha(1f);
60 | }else {
61 | holder.itemView.setAlpha(0.3f);
62 | }
63 | holder.mTvContent.setText(waterMarkConfig.getContent());
64 | holder.mCardView.setOnTouchListener((v, event) -> {
65 | if (event.getAction() == MotionEvent.ACTION_DOWN) {
66 | lastTouchPosition.set((int) event.getX(), (int) event.getY());
67 | }
68 | return false;
69 | });
70 | holder.mCardView.setOnClickListener(v -> {
71 | Intent startIntentWithConfig = EditConfigActivity.getStartIntentWithConfig(mContext, waterMarkConfig);
72 | mResultLauncher.launch(startIntentWithConfig);
73 | });
74 | holder.mCardView.setOnLongClickListener(v -> {
75 | showPopupWindow(v, waterMarkConfig);
76 | return true;
77 | });
78 | }
79 |
80 | @Override
81 | public int getItemCount() {
82 | return mWaterMarkConfigs.size();
83 | }
84 |
85 | private void showPopupWindow(View view, WaterMarkConfig waterMarkConfig){
86 | int dip2px = DensityUtils.dip2px(mContext, 100);
87 | PopupWindow popupWindow = new PopupWindow(dip2px, dip2px);
88 | popupWindow.setTouchable(true);
89 | popupWindow.setFocusable(true);
90 | popupWindow.setOutsideTouchable(true);
91 | View rootView = View.inflate(mContext, R.layout.popup_action, null);
92 | Button mbState = rootView.findViewById(R.id.mb_state);
93 | Button mbDelete = rootView.findViewById(R.id.mb_delete);
94 | if(waterMarkConfig.isOpen){
95 | mbState.setText("禁用");
96 | }else {
97 | mbState.setText("启用");
98 | }
99 | mbState.setOnClickListener(v -> {
100 | waterMarkConfig.setOpen(!waterMarkConfig.isOpen);
101 | ConfigHelper.saveWaterMarkConfig(mContext, waterMarkConfig);
102 | notifyDataSetChanged();
103 | popupWindow.dismiss();
104 | });
105 | mbDelete.setOnClickListener(v -> {
106 | ConfigHelper.deleteWaterMarkConfig(mContext, waterMarkConfig);
107 | notifyDataSetChanged();
108 | popupWindow.dismiss();
109 | });
110 | popupWindow.setContentView(rootView);
111 | Log.d("yys ", "showPopupWindow: " + lastTouchPosition);
112 | popupWindow.showAsDropDown(view, lastTouchPosition.x, lastTouchPosition.y - view.getMeasuredHeight(), Gravity.NO_GRAVITY);
113 |
114 | }
115 | }
116 |
117 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/NetWorkUtil.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import android.app.Application;
4 | import android.os.Handler;
5 |
6 | import java.io.BufferedReader;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.io.InputStreamReader;
10 | import java.io.OutputStream;
11 | import java.io.UnsupportedEncodingException;
12 | import java.net.HttpURLConnection;
13 | import java.net.URL;
14 | import java.net.URLEncoder;
15 |
16 | public class NetWorkUtil {
17 |
18 | private volatile static NetWorkUtil mInstance;
19 | private static Application mApplication;
20 |
21 | private NetWorkUtil() {
22 | }
23 |
24 | public static NetWorkUtil getInstance(Application application) {
25 | mApplication = application;
26 | if (mInstance == null) {
27 | synchronized (NetWorkUtil.class) {
28 | if (mInstance == null) {
29 | mInstance = new NetWorkUtil();
30 | }
31 | }
32 | }
33 | return mInstance;
34 | }
35 |
36 | public void requestByGet(String urlStr,NetWorkCallback callback) {
37 | new Thread(() -> {
38 | try {
39 | URL url = new URL(urlStr);
40 | HttpURLConnection connection = (HttpURLConnection) url.openConnection();
41 | connection.setConnectTimeout(30 * 1000);//设置超时时长,单位ms
42 | connection.setRequestMethod("GET");//设置请求格式
43 | connection.setRequestProperty("Content-Type", "Application/json");//期望返回的数据格式
44 | connection.setRequestProperty("CharSet", "UTF-8");//设置字符集
45 | connection.setRequestProperty("Accept-CharSet", "UTF-8");//请求的字符集
46 | connection.connect();//发送请求
47 |
48 | int responseCode = connection.getResponseCode();//获取返回码
49 | String json = getJson(connection);
50 | runOnUiThread(() -> {
51 | if(callback == null){
52 | return;
53 | }
54 | if (responseCode == HttpURLConnection.HTTP_OK) {
55 | callback.onSuccess(json);
56 | }else {
57 | callback.onFail("!OK");
58 | }
59 | });
60 | } catch (IOException e) {
61 | LogUtil.e(e.getMessage());
62 | e.printStackTrace();
63 | }
64 | }).start();
65 | }
66 |
67 | private String getJson(HttpURLConnection connection){
68 | InputStream in;
69 | try {
70 | in = connection.getInputStream();
71 | BufferedReader reader = new BufferedReader(new InputStreamReader(in));
72 | StringBuilder html = new StringBuilder();
73 | for (String line; (line = reader.readLine()) != null; ) {
74 | html.append(line);
75 | }
76 | in.close();
77 | return html.toString().trim();
78 | } catch (IOException e) {
79 | e.printStackTrace();
80 | }
81 | return null;
82 | }
83 |
84 | private void runOnUiThread(Runnable runnable) {
85 | Handler handler = new Handler(mApplication.getMainLooper());
86 | handler.post(runnable);
87 | }
88 |
89 | private void requestByPost(String urlStr) {
90 | try {
91 | URL url = new URL(urlStr);
92 | HttpURLConnection connection = (HttpURLConnection) url.openConnection();
93 | connection.setConnectTimeout(30 * 1000);//设置超时时长,单位ms
94 | connection.setRequestMethod("GET");//设置请求格式
95 | connection.setRequestProperty("Content-Type", "Application/json");//期望返回的数据格式
96 | connection.setRequestProperty("CharSet", "UTF-8");//设置字符集
97 | connection.setRequestProperty("Accept-CharSet", "UTF-8");//请求的字符集
98 |
99 | connection.setUseCaches(false);//设置缓存使用
100 | connection.setDoInput(true);//设置输入流使用
101 | connection.setDoOutput(true);//设置输出流使用
102 | connection.connect();
103 |
104 | String data = "username=" + getEncodeValue("小王") + "&number=" + getEncodeValue(
105 | "123456");
106 | OutputStream outputStream = connection.getOutputStream();//获取到输出流
107 | outputStream.write(data.getBytes());//写入数据
108 | outputStream.flush();//执行
109 | outputStream.close();//关闭
110 |
111 | int responseCode = connection.getResponseCode();
112 | String responseMessage = connection.getResponseMessage();
113 | if (responseCode == HttpURLConnection.HTTP_OK) {
114 | //TODO
115 | }
116 |
117 | runOnUiThread(() -> {
118 |
119 | });
120 | } catch (IOException e) {
121 | e.printStackTrace();
122 | }
123 | }
124 |
125 | private String getEncodeValue(String name) {
126 | String encode = null;
127 |
128 | try {
129 | encode = URLEncoder.encode(name, "UTF-8");
130 | } catch (UnsupportedEncodingException e) {
131 | e.printStackTrace();
132 | }
133 | return encode;
134 | }
135 |
136 | public interface NetWorkCallback{
137 | void onSuccess(T result);
138 | void onFail(String msg);
139 | void onCancel(String msg);
140 | }
141 |
142 | }
143 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/OpeConfigFromSp.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import static com.xiaoer.watermark.bean.SPContact.APP_CONFIG;
4 | import static com.xiaoer.watermark.bean.SPContact.WATER_MARK_CONFIG_FILE_NAME;
5 | import static com.xiaoer.watermark.bean.SPContact.WATER_MARK_CONFIG_KEY;
6 |
7 | import android.content.Context;
8 | import android.content.SharedPreferences;
9 | import android.text.TextUtils;
10 |
11 | import com.google.gson.Gson;
12 | import com.xiaoer.watermark.BuildConfig;
13 | import com.xiaoer.watermark.bean.AppConfig;
14 | import com.xiaoer.watermark.bean.SPContact;
15 | import com.xiaoer.watermark.bean.WaterMarkConfig;
16 |
17 | import java.util.ArrayList;
18 | import java.util.HashSet;
19 | import java.util.List;
20 | import java.util.Set;
21 |
22 | import de.robv.android.xposed.XSharedPreferences;
23 |
24 | public class OpeConfigFromSp {
25 |
26 | public static SharedPreferences mSharedPreferences;
27 | public static XSharedPreferences mXsp;
28 |
29 | private static volatile OpeConfigFromSp mOpeConfigFromSp;
30 |
31 | private OpeConfigFromSp(){}
32 |
33 | public static OpeConfigFromSp getInstance(){
34 | if (mOpeConfigFromSp == null){
35 | synchronized (OpeConfigFromSp.class){
36 | if (mOpeConfigFromSp == null){
37 | mOpeConfigFromSp = new OpeConfigFromSp();
38 | }
39 | }
40 | }
41 | return mOpeConfigFromSp;
42 | }
43 |
44 |
45 | public void saveAppConfig(Context context, AppConfig config) {
46 | LogUtil.d("OpeConfigFromSp saveAppConfig:" + config);
47 | getEdit(context).putString(APP_CONFIG, new Gson().toJson(config)).apply();
48 | }
49 |
50 | public AppConfig getAppConfig(Context context){
51 | AppConfig appConfig = new Gson().fromJson(getSp(context).getString(APP_CONFIG, ""), AppConfig.class);
52 | LogUtil.d("OpeConfigFromSp cache appConfig: " + (appConfig == null ? "null" : appConfig));
53 | return appConfig;
54 | }
55 |
56 | public List getWaterMarkConfigs(Context context) {
57 | SharedPreferences sharedPreferences = getSp(context);
58 | Set stringSet = sharedPreferences.getStringSet(WATER_MARK_CONFIG_KEY, null);
59 | ArrayList result = new ArrayList<>();
60 | if (stringSet != null && stringSet.size() > 0) {
61 | for (String item : stringSet) {
62 | result.add(new Gson().fromJson(item, WaterMarkConfig.class));
63 | }
64 | }
65 | LogUtil.d("OpeConfigFromSp---getWaterMarkConfigs: " + result);
66 | return result;
67 | }
68 |
69 | public WaterMarkConfig getCurrentAppConfig(Context context) {
70 | List waterMarkConfigs = getWaterMarkConfigs(context);
71 | for (WaterMarkConfig item : waterMarkConfigs) {
72 | if (item.isOpen() && item.packageList != null && item.packageList.contains(context.getPackageName())) {
73 | return item;
74 | }
75 | }
76 | return new WaterMarkConfig();
77 | }
78 |
79 | public void saveWaterMarkConfig(Context context, WaterMarkConfig config){
80 | if(config == null){
81 | return;
82 | }
83 | List waterMarkConfigs = getWaterMarkConfigs(context);
84 | HashSet result = new HashSet<>();
85 | Gson gson = new Gson();
86 | result.add(gson.toJson(config));
87 | for (WaterMarkConfig waterMarkConfig : waterMarkConfigs) {
88 | if (!TextUtils.equals(waterMarkConfig.configId, config.configId)) {
89 | result.add(gson.toJson(waterMarkConfig));
90 | }
91 | }
92 | LogUtil.d("saveWaterMarkConfig:" + result);
93 | getEdit(context).putStringSet(WATER_MARK_CONFIG_KEY, result).apply();
94 | }
95 |
96 | public void deleteWaterMarkConfig(Context context, WaterMarkConfig config){
97 | if(config == null){
98 | return;
99 | }
100 | List waterMarkConfigs = getWaterMarkConfigs(context);
101 | HashSet result = new HashSet<>();
102 | Gson gson = new Gson();
103 | for (WaterMarkConfig waterMarkConfig : waterMarkConfigs) {
104 | if (!TextUtils.equals(waterMarkConfig.configId, config.configId)) {
105 | result.add(gson.toJson(waterMarkConfig));
106 | }
107 | }
108 | LogUtil.d("deleteWaterMarkConfig:" + result);
109 | getEdit(context).putStringSet(WATER_MARK_CONFIG_KEY, result).apply();
110 | }
111 |
112 | public SharedPreferences getSp(Context context) {
113 | if(isXposedModule(context)){
114 | LogUtil.d("use SP");
115 | return getCommonSp(context);
116 | }else {
117 | LogUtil.d("use XSP");
118 | return getXSharedPreferences();
119 | }
120 | }
121 |
122 | private SharedPreferences getXSharedPreferences(){
123 | if(mXsp == null){
124 | mXsp = new XSharedPreferences(BuildConfig.APPLICATION_ID, WATER_MARK_CONFIG_FILE_NAME);
125 | }
126 | return mXsp;
127 | }
128 |
129 | private SharedPreferences getCommonSp(Context context){
130 | if(mSharedPreferences == null){
131 | mSharedPreferences = context.getSharedPreferences(WATER_MARK_CONFIG_FILE_NAME, Context.MODE_PRIVATE);
132 | }
133 | return mSharedPreferences;
134 | }
135 |
136 | private boolean isXposedModule(Context context){
137 | return BuildConfig.APPLICATION_ID.equals(context.getPackageName());
138 | }
139 |
140 | private SharedPreferences.Editor getEdit(Context context){
141 | return getCommonSp(context).edit();
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/edit/SelectPackageActivity.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.edit;
2 |
3 | import static com.xiaoer.watermark.ui.edit.EditConfigActivity.REQUEST_CONFIG_KEY;
4 |
5 | import android.annotation.SuppressLint;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.content.pm.PackageInfo;
9 | import android.os.Bundle;
10 | import android.view.Menu;
11 | import android.view.MenuItem;
12 | import android.view.inputmethod.EditorInfo;
13 | import android.webkit.ValueCallback;
14 |
15 | import androidx.annotation.Nullable;
16 | import androidx.appcompat.app.AppCompatActivity;
17 | import androidx.appcompat.widget.SearchView;
18 | import androidx.recyclerview.widget.LinearLayoutManager;
19 | import androidx.recyclerview.widget.RecyclerView;
20 | import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
21 |
22 | import com.xiaoer.watermark.R;
23 | import com.xiaoer.watermark.bean.WaterMarkConfig;
24 | import com.xiaoer.watermark.hook.ConfigHelper;
25 |
26 | import java.util.ArrayList;
27 |
28 | public class SelectPackageActivity extends AppCompatActivity {
29 |
30 | private ArrayList mInstalledPackages;
31 |
32 | private WaterMarkConfig originConfig;
33 | private SwipeRefreshLayout mSrlRoot;
34 | private SelectPackageAdapter mSelectPackageAdapter;
35 | private WaterMarkConfig mWaterMarkConfig;
36 | private RecyclerView mRvAppList;
37 | private SearchView mSearchView;
38 |
39 | public static Intent getStartIntent(Context context){
40 | return new Intent(context, SelectPackageActivity.class);
41 | }
42 |
43 | public static Intent getStartIntentWithConfig(Context context, WaterMarkConfig waterMarkConfig){
44 | Intent startIntent = getStartIntent(context);
45 | startIntent.putExtra(REQUEST_CONFIG_KEY, waterMarkConfig);
46 | return startIntent;
47 | }
48 |
49 | @Override
50 | protected void onCreate(@Nullable Bundle savedInstanceState) {
51 | super.onCreate(savedInstanceState);
52 | setContentView(R.layout.activity_select_app);
53 |
54 | initData();
55 | initView();
56 |
57 | }
58 |
59 | @SuppressLint("NotifyDataSetChanged")
60 | private void initView() {
61 | mRvAppList = findViewById(R.id.rv_appList);
62 | mSrlRoot = findViewById(R.id.srl_root);
63 |
64 | mSrlRoot.setOnRefreshListener(() -> {
65 | if(mSearchView.hasFocus()){
66 | mSearchView.clearFocus();
67 | }else {
68 | if (mSelectPackageAdapter != null){
69 | mSelectPackageAdapter.updateSelectList(value -> mSrlRoot.post(() -> mSelectPackageAdapter.notifyDataSetChanged()));
70 | }
71 | }
72 | mSrlRoot.setRefreshing(false);
73 | });
74 |
75 | LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
76 | linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
77 | mSelectPackageAdapter = new SelectPackageAdapter(this, mInstalledPackages, mWaterMarkConfig.getAppList());
78 | mRvAppList.setAdapter(mSelectPackageAdapter);
79 | mRvAppList.setLayoutManager(linearLayoutManager);
80 | }
81 |
82 | private void initData() {
83 | if(getIntent() != null && getIntent().getSerializableExtra(REQUEST_CONFIG_KEY) instanceof WaterMarkConfig){
84 | mWaterMarkConfig = (WaterMarkConfig) getIntent().getSerializableExtra(REQUEST_CONFIG_KEY);
85 | }
86 | originConfig = mWaterMarkConfig;
87 | mInstalledPackages = (ArrayList) getPackageManager().getInstalledPackages(0);
88 | }
89 |
90 | @Override
91 | public boolean onCreateOptionsMenu(Menu menu) {
92 | //引用menu文件
93 | getMenuInflater().inflate(R.menu.menu_search, menu);
94 | MenuItem save = menu.findItem(R.id.menu_save);
95 | save.setOnMenuItemClickListener(item -> {
96 | if(mSelectPackageAdapter != null){
97 | mWaterMarkConfig.setAppList(mSelectPackageAdapter.getSelectAppList());
98 | finishEdit();
99 | }
100 | return true;
101 | });
102 |
103 | // //找到SearchView并配置相关参数
104 | MenuItem searchItem = menu.findItem(R.id.menu_search);
105 | mSearchView = (SearchView) searchItem.getActionView();
106 | mSearchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
107 | // //设置提示词
108 | mSearchView.setQueryHint("搜索应用");
109 | @SuppressLint("NotifyDataSetChanged")
110 | ValueCallback filterCallback = value -> {
111 | if(mSelectPackageAdapter != null){
112 | runOnUiThread(() -> mSelectPackageAdapter.notifyDataSetChanged());
113 | }
114 | };
115 | mSearchView.setOnQueryTextFocusChangeListener((v, hasFocus) -> {
116 | if(!hasFocus){
117 | if(mSelectPackageAdapter != null){
118 | mSelectPackageAdapter.filterPackage("", filterCallback);
119 | }
120 | }
121 | });
122 | mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
123 | @Override
124 | public boolean onQueryTextSubmit(String query) {
125 | return false;
126 | }
127 |
128 | @Override
129 | public boolean onQueryTextChange(String newText) {
130 | if(mSelectPackageAdapter != null){
131 | mSelectPackageAdapter.filterPackage(newText, filterCallback);
132 | }
133 | return false;
134 | }
135 | });
136 | return super.onCreateOptionsMenu(menu);
137 | }
138 |
139 | public void finishEdit(){
140 | Intent data = new Intent();
141 | data.putExtra("result", mWaterMarkConfig);
142 | setResult(RESULT_OK, data);
143 | finish();
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/ProcessUtil.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import android.app.ActivityManager;
4 | import android.app.Application;
5 | import android.content.Context;
6 | import android.os.Build;
7 | import android.text.TextUtils;
8 |
9 | import com.xiaoer.watermark.hook.AddWaterMark;
10 |
11 | import java.io.BufferedReader;
12 | import java.io.FileInputStream;
13 | import java.io.FileNotFoundException;
14 | import java.io.IOException;
15 | import java.io.InputStreamReader;
16 | import java.util.List;
17 |
18 | public class ProcessUtil {
19 | private static final String TAG = "ProcessUtil";
20 |
21 | public static boolean isMainProcess() {
22 | return isProcess(getPackageName());
23 | }
24 |
25 | public static boolean isPatchProcess() {
26 | return isProcess(getPackageName() + ":patch");
27 | }
28 |
29 | public static boolean isSafeModeProcess() {
30 | return isProcess(getPackageName() + ":safeMode");
31 | }
32 |
33 | public static boolean isErrorProcess() {
34 | return isProcess(getPackageName() + ":error");
35 | }
36 |
37 | public static boolean isWatchDogProcess() {
38 | return isProcess(getPackageName() + ":WatchDogService");
39 | }
40 |
41 | public static boolean isPushProcess() {
42 | return isProcess(getPackageName() + ":jdpush") || isProcess(getPackageName() + ":pushservice");
43 | }
44 |
45 | /********
46 | * 用于application加载优化
47 | *
48 | * @param pid 当前Application进程PID
49 | * @return String 返回进程名称
50 | *****/
51 | public static String getProcessName(int pid) {
52 | InputStreamReader reader = null;
53 | BufferedReader br = null;
54 | try {
55 | reader = new InputStreamReader(new FileInputStream("/proc/" + pid + "/cmdline"));
56 | br = new BufferedReader(reader);
57 | char[] data = new char[64];//定义数组 进程名字最长64
58 | br.read(data);
59 | int len = 0;
60 | for (char c : data) {//因为cmdline文件不再文件系统,如果直接readline截取的数据过多
61 | if (c == 0) {
62 | break;
63 | }
64 | len++;
65 | }
66 | return new String(data, 0, len);//daString.startsWith("com.jingdong.app.mall:");
67 | } catch (FileNotFoundException e) {
68 | } catch (IOException e) {
69 | } finally {
70 | if (reader != null) {
71 | try {
72 | reader.close();
73 | } catch (IOException e) {
74 | }
75 | }
76 | if (br != null) {
77 | try {
78 | br.close();
79 | } catch (IOException e) {
80 | }
81 | }
82 |
83 | }
84 | return "";
85 |
86 | }
87 |
88 | /**
89 | * 应用是否处于前台
90 | *
91 | * @return
92 | */
93 | public static boolean isForeground() {
94 |
95 | ActivityManager activityManager = (ActivityManager) AddWaterMark.getApplication().getSystemService(Context.ACTIVITY_SERVICE);
96 | List appProcesses = activityManager.getRunningAppProcesses();
97 | if (appProcesses == null)
98 | return false;
99 | for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
100 | if (appProcess.processName.equals(AddWaterMark.getApplication().getPackageName())) {
101 | if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {//IMPORTANCE_BACKGROUND
102 | return true;
103 | } else {
104 | return false;
105 | }
106 |
107 | }
108 | }
109 | return false;
110 | }
111 |
112 | public static boolean isProcess(String pName){
113 | if(TextUtils.isEmpty(pName))
114 | return false;
115 | String processName=null;
116 | try {
117 | processName = getProcessName(AddWaterMark.getApplication());
118 | if (processName == null || processName.length() == 0) {
119 | processName = "";
120 | }
121 | }catch (Throwable e){}
122 | if(TextUtils.isEmpty(processName)){
123 | processName = getProcessName(android.os.Process.myPid()).trim();
124 | }
125 | return pName.equals(processName);
126 | }
127 |
128 | private static String processName = null;
129 |
130 | /**
131 | * add process name cache
132 | *
133 | * @param context
134 | * @return
135 | */
136 | public static String getProcessName(final Context context) {
137 | if (processName != null) {
138 | return processName;
139 | }
140 | //will not null
141 | processName = getProcessNameInternal(context);
142 | return processName;
143 | }
144 |
145 | private static String getProcessNameInternal(final Context context) {
146 | String process = "";
147 | if(!TextUtils.isEmpty(process)){
148 | return process;
149 | }
150 | int myPid = android.os.Process.myPid();
151 | if (context == null || myPid <= 0) {
152 | return "";
153 | }
154 | byte[] b = new byte[128];
155 | try (FileInputStream in = new FileInputStream("/proc/" + myPid + "/cmdline")) {
156 | int len = in.read(b);
157 | if (len > 0) {
158 | for (int i = 0; i < len; i++) { // lots of '0' in tail , remove them
159 | if (b[i] <= 0) {
160 | len = i;
161 | break;
162 | }
163 | }
164 | return new String(b, 0, len);
165 | }
166 |
167 | } catch (Throwable e) {/**/}
168 | /**/
169 |
170 | return "";
171 | }
172 |
173 | private static String getPackageName(){
174 | return AddWaterMark.getApplication().getPackageName();
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/main/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.main;
2 |
3 |
4 | import static com.xiaoer.watermark.hook.ConfigHelper.isModuleActivated;
5 |
6 | import android.annotation.SuppressLint;
7 | import android.content.Intent;
8 | import android.os.Bundle;
9 | import android.view.Menu;
10 | import android.view.MenuItem;
11 | import android.view.View;
12 | import android.widget.ImageView;
13 | import android.widget.TextView;
14 |
15 | import androidx.activity.result.ActivityResultLauncher;
16 | import androidx.activity.result.contract.ActivityResultContracts;
17 | import androidx.appcompat.app.AppCompatActivity;
18 | import androidx.appcompat.content.res.AppCompatResources;
19 | import androidx.recyclerview.widget.LinearLayoutManager;
20 | import androidx.recyclerview.widget.RecyclerView;
21 | import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
22 |
23 | import com.google.android.material.card.MaterialCardView;
24 | import com.google.android.material.dialog.MaterialAlertDialogBuilder;
25 | import com.google.android.material.floatingactionbutton.FloatingActionButton;
26 | import com.google.android.material.textview.MaterialTextView;
27 | import com.xiaoer.watermark.BuildConfig;
28 | import com.xiaoer.watermark.R;
29 | import com.xiaoer.watermark.bean.WaterMarkConfig;
30 | import com.xiaoer.watermark.hook.ConfigHelper;
31 | import com.xiaoer.watermark.ui.edit.EditConfigActivity;
32 |
33 | import java.util.ArrayList;
34 | import java.util.List;
35 |
36 | public class MainActivity extends AppCompatActivity {
37 |
38 | public SwipeRefreshLayout mSrflRoot;
39 | public RecyclerView mRvConfigs;
40 | public MaterialCardView mModuleStatusCard;
41 | public ImageView mIvStatusIcon;
42 | public TextView mTvModuleStatus;
43 | public TextView mTvServiceStatus;
44 | public FloatingActionButton mFabAdd;
45 | private ActivityResultLauncher mResultLauncher;
46 | private List mWaterMarkConfigs = new ArrayList<>();
47 | private MainActivityHandler mMainActivityHandler;
48 | private ConfigAdapter mConfigAdapter;
49 |
50 | @Override
51 | protected void onCreate(Bundle savedInstanceState) {
52 | super.onCreate(savedInstanceState);
53 | setContentView(R.layout.activity_main);
54 |
55 | mMainActivityHandler = new MainActivityHandler(MainActivity.this);
56 | mResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
57 | if (result.getResultCode() == RESULT_OK) {
58 | updateConfigData();
59 | }
60 | });
61 |
62 | initView();
63 | }
64 |
65 | private void initView() {
66 | mSrflRoot = findViewById(R.id.srfl_root);
67 | mRvConfigs = findViewById(R.id.rv_config);
68 | mModuleStatusCard = findViewById(R.id.module_status_card);
69 | mIvStatusIcon = findViewById(R.id.module_status_icon);
70 | mTvModuleStatus = findViewById(R.id.module_status_text);
71 | mTvServiceStatus = findViewById(R.id.service_status_text);
72 | mFabAdd = findViewById(R.id.fab_add);
73 |
74 | setModuleState();
75 | initReceiverView();
76 |
77 | mSrflRoot.setOnRefreshListener(this::updateConfigData);
78 | mFabAdd.setOnClickListener(v -> {
79 | Intent startIntent = EditConfigActivity.getStartIntent(MainActivity.this);
80 | mResultLauncher.launch(startIntent);
81 | });
82 |
83 | }
84 |
85 | @Override
86 | public boolean onCreateOptionsMenu(Menu menu) {
87 | MenuItem aboutMe = menu.add("");
88 | aboutMe.setIcon(R.drawable.baseline_about_us);
89 | aboutMe.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
90 | aboutMe.setOnMenuItemClickListener(item -> {
91 | MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(MainActivity.this, R.style.MyThemeOverlayAlertDialog);
92 | View rootView = View.inflate(MainActivity.this, R.layout.dialog_about_me, null);
93 | MaterialTextView mtvAppVersion = rootView.findViewById(R.id.mtv_app_version);
94 | mtvAppVersion.setText(BuildConfig.VERSION_NAME);
95 | builder.setView(rootView);
96 | builder.setCancelable(true);
97 | builder.show();
98 | return true;
99 | });
100 | return super.onCreateOptionsMenu(menu);
101 | }
102 |
103 | private void updateConfigData() {
104 | if(mSrflRoot != null){
105 | mSrflRoot.setRefreshing(true);
106 | }
107 | new Thread(() -> {
108 | mWaterMarkConfigs = ConfigHelper.getWaterMarkConfigs(getApplicationContext());
109 | mMainActivityHandler.sendEmptyMessage(MainActivityHandler.OK);
110 | }).start();
111 | }
112 |
113 | @SuppressLint("NotifyDataSetChanged")
114 | public void updateRecyclerView(){
115 | if(mConfigAdapter != null){
116 | mConfigAdapter.setWaterMarkConfigs(mWaterMarkConfigs);
117 | mConfigAdapter.notifyDataSetChanged();
118 | mSrflRoot.setRefreshing(false);
119 | }
120 | }
121 |
122 | private void initReceiverView() {
123 | mConfigAdapter = new ConfigAdapter(MainActivity.this, mWaterMarkConfigs, mResultLauncher);
124 | LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
125 | linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
126 | mRvConfigs.setLayoutManager(linearLayoutManager);
127 | mRvConfigs.setAdapter(mConfigAdapter);
128 | updateConfigData();
129 | }
130 |
131 | public void setModuleState(){
132 | if (isModuleActivated()) {
133 | mModuleStatusCard.setCardBackgroundColor(getColor(R.color.purple_500));
134 | mIvStatusIcon.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.baseline_check_circle_24));
135 | mTvModuleStatus.setText(getString(R.string.card_title_activated));
136 | mTvServiceStatus.setText(R.string.card_detail_activated);
137 |
138 | } else {
139 | mModuleStatusCard.setCardBackgroundColor(getColor(R.color.red_500));
140 | mIvStatusIcon.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.baseline_error_24));
141 | mTvModuleStatus.setText(getString(R.string.card_title_not_activated));
142 | mTvServiceStatus.setText(R.string.card_detail_not_activated);
143 | }
144 | }
145 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/hook/WaterMarkManager.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.hook;
2 |
3 |
4 | import android.Manifest;
5 | import android.app.Activity;
6 | import android.app.Application;
7 | import android.content.Context;
8 | import android.content.pm.PackageInfo;
9 | import android.content.pm.PackageManager;
10 | import android.widget.Toast;
11 |
12 | import com.google.gson.Gson;
13 | import com.xiaoer.watermark.bean.AppConfig;
14 | import com.xiaoer.watermark.bean.WaterMarkConfig;
15 | import com.xiaoer.watermark.ui.Watermark;
16 | import com.xiaoer.watermark.util.LogUtil;
17 | import com.xiaoer.watermark.util.NetWorkUtil;
18 |
19 | import java.util.concurrent.ConcurrentHashMap;
20 | import java.util.concurrent.atomic.AtomicBoolean;
21 |
22 | public class WaterMarkManager {
23 |
24 | private static WaterMarkManager mManager;
25 | private final AtomicBoolean canShow = new AtomicBoolean();
26 | private static WaterMarkConfig mWaterMarkConfig;
27 | private final ConcurrentHashMap mHashMap = new ConcurrentHashMap<>();
28 |
29 | private WaterMarkManager(){
30 | }
31 |
32 | public static WaterMarkManager getInstance(){
33 | if(mManager == null){
34 | synchronized (WaterMarkManager.class){
35 | mManager = new WaterMarkManager();
36 | }
37 | }
38 | return mManager;
39 | }
40 |
41 | public static void init(Application application){
42 | final boolean initByCache;
43 | AppConfig appConfig = ConfigHelper.getAppConfig(application);
44 |
45 | if(appConfig != null){
46 | initByCache = true;
47 | handleAppConfig(application, appConfig);
48 | }else {
49 | initByCache = false;
50 | }
51 |
52 | if (application.checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED){
53 | NetWorkUtil.getInstance(application).requestByGet("https://www.2ys.club/waterMark/queryAppConfig", new NetWorkUtil.NetWorkCallback() {
54 | @Override
55 | public void onSuccess(String result) {
56 | try {
57 | AppConfig appConfig = new Gson().fromJson(result, AppConfig.class);
58 | if(!initByCache){
59 | LogUtil.d("use net appConfig");
60 | handleAppConfig(application, appConfig);
61 | }
62 | ConfigHelper.saveAppConfig(application, appConfig);
63 | }catch (Exception e){
64 | WaterMarkManager.getInstance().canShow.set(true);
65 | Toast.makeText(application,"读取网络配置失败",Toast.LENGTH_SHORT).show();
66 | LogUtil.e("onSuccess:" + e.getMessage());
67 | }
68 | }
69 |
70 | @Override
71 | public void onFail(String msg) {
72 | WaterMarkManager.getInstance().canShow.set(true);
73 | Toast.makeText(application,"读取网络配置失败",Toast.LENGTH_SHORT).show();
74 | LogUtil.e("请求失败,无法显示水印");
75 | }
76 |
77 | @Override
78 | public void onCancel(String msg) {
79 | WaterMarkManager.getInstance().canShow.set(true);
80 | Toast.makeText(application,"读取网络配置失败",Toast.LENGTH_SHORT).show();
81 | }
82 | });
83 | }else {
84 | LogUtil.e("no internet permission");
85 | WaterMarkManager.getInstance().canShow.set(true);
86 | }
87 |
88 | initWaterMarkConfig(application);
89 | }
90 |
91 | private static void handleAppConfig(Context context, AppConfig configBean) {
92 | if (context == null){
93 | return;
94 | }
95 | String pkgName;
96 | String versionName;
97 | PackageManager packageManager = context.getPackageManager();
98 | try {
99 | PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
100 | pkgName = packageInfo.packageName;
101 | versionName = packageInfo.versionName;
102 | } catch (PackageManager.NameNotFoundException e) {
103 | LogUtil.d("获取宿主包名或版本名失败,无法显示水印");
104 | Toast.makeText(context,"获取宿主包名或版本名失败,无法显示水印",Toast.LENGTH_SHORT).show();
105 | return;
106 | }
107 | LogUtil.d("pkgName: " + pkgName + " versionName: " + versionName);
108 | boolean matchPkg = false;
109 | boolean matchVer = false;
110 | if(configBean == null){
111 | WaterMarkManager.getInstance().canShow.set(true);
112 | return;
113 | }
114 | if(configBean.getCode() == 1){
115 | LogUtil.d("开关关闭,开放所有");
116 | WaterMarkManager.getInstance().canShow.set(true);
117 | }else {
118 | if(configBean.getAppList() != null && configBean.getAppList().size() > 0){
119 | for (AppConfig.AppBean appBean : configBean.getAppList()) {
120 | if (appBean.getPackageName().equals(pkgName)) {
121 | matchPkg = true;
122 | for (String s : appBean.getVersionCode()) {
123 | if (s.equals(versionName)) {
124 | matchVer = true;
125 | break;
126 | }
127 | }
128 | break;
129 | }
130 | }
131 | }
132 | LogUtil.d("matchPkg: " + matchPkg + " matchVer: " + matchVer);
133 | if(matchPkg){
134 | if(matchVer){
135 | WaterMarkManager.getInstance().canShow.set(true);
136 | }else {
137 | WaterMarkManager.getInstance().canShow.set(false);
138 | Toast.makeText(context, "未适配当前应用的版本", Toast.LENGTH_SHORT).show();
139 | }
140 | }else {
141 | WaterMarkManager.getInstance().canShow.set(true);
142 | }
143 | }
144 | }
145 |
146 | private static void initWaterMarkConfig(Context context){
147 | LogUtil.d("initWaterMarkConfig: " + context.getPackageName());
148 | mWaterMarkConfig = ConfigHelper.getCurrentAppConfig(context);
149 | }
150 |
151 | public void addWaterMark(Activity activity){
152 | if (canShow.get() && mWaterMarkConfig != null) {
153 | Watermark watermark = null;
154 | if (mHashMap.containsKey(activity.getLocalClassName())) {
155 | watermark = mHashMap.get(activity.getLocalClassName());
156 | }
157 | if (watermark == null){
158 | watermark = new Watermark(activity);
159 | watermark.setText(mWaterMarkConfig.getContent());
160 | watermark.setTextColor(mWaterMarkConfig.getTextColor());
161 | watermark.setTextSize(mWaterMarkConfig.getTextSize());
162 | watermark.setRotation(mWaterMarkConfig.getRotation());
163 | }
164 | watermark.show();
165 | }
166 | }
167 |
168 | public void removeWaterMark(Activity activity){
169 | mHashMap.remove(activity.getLocalClassName());
170 | }
171 |
172 | }
173 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/util/FileUtils.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.util;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.ActivityManager;
5 | import android.content.Context;
6 | import android.net.Uri;
7 | import android.text.TextUtils;
8 | import android.util.Log;
9 |
10 | import com.github.kyuubiran.ezxhelper.HookFactory;
11 | import com.github.kyuubiran.ezxhelper.finders.MethodFinder;
12 | import com.xiaoer.watermark.BuildConfig;
13 |
14 | import org.lsposed.hiddenapibypass.HiddenApiBypass;
15 |
16 | import java.io.ByteArrayOutputStream;
17 | import java.io.File;
18 | import java.io.FileInputStream;
19 | import java.io.FileOutputStream;
20 | import java.io.FileWriter;
21 | import java.io.IOException;
22 | import java.io.InputStream;
23 | import java.lang.reflect.Method;
24 | import java.nio.charset.StandardCharsets;
25 | import java.util.Locale;
26 | import java.util.concurrent.ConcurrentHashMap;
27 |
28 | import de.robv.android.xposed.callbacks.XC_LoadPackage;
29 |
30 | public class FileUtils {
31 | private static volatile FileUtils instance;
32 | private static final String SCHEME = "xiaoer";
33 | private static final String KEY_ACTION = "action";
34 | private static final String KEY_FILE_NAME = "fileName";
35 | private static final String KEY_FILE_DATA = "fileData";
36 | public static final String ROOT_PATH = "/data/system/";
37 |
38 | public static final int HOOK_TAG = 1248774172;
39 |
40 | public static final String ACTION_READ_FILE = "readFile";
41 | public static final String ACTION_WRITE_FILE = "writeFile";
42 |
43 | public static final String ACTION_DELETE_FILE = "deleteFile";
44 |
45 | private static final ConcurrentHashMap mFileDataCache = new ConcurrentHashMap<>();
46 |
47 | private String dataDir;
48 |
49 | private FileUtils() {
50 | }
51 |
52 | public static FileUtils getInstance() {
53 | if (instance == null) {
54 | synchronized (FileUtils.class) {
55 | if (instance == null) {
56 | instance = new FileUtils();
57 | }
58 | }
59 | }
60 | return instance;
61 | }
62 |
63 | public void initZygote() {
64 | String name = BuildConfig.APPLICATION_ID.replaceAll("\\.", "_");
65 | dataDir = ROOT_PATH + name;
66 | logD("setDataPath: " + dataDir);
67 | }
68 |
69 | @SuppressLint("PrivateApi")
70 | public void hookAMS(XC_LoadPackage.LoadPackageParam lpparam) throws ClassNotFoundException {
71 | Class> aClass = lpparam.classLoader.loadClass("com.android.server.am.ActivityManagerService");
72 | MethodFinder methodFinder = MethodFinder.fromClass(aClass);
73 | Method method = methodFinder.filterByName("setProcessMemoryTrimLevel").first();
74 | HookFactory.createMethodHook(method, hookFactory -> hookFactory.before(param -> {
75 | String url = (String) param.args[0];
76 | int tag = (int) param.args[1];
77 | if (tag == HOOK_TAG) {
78 | if(TextUtils.isEmpty(url)){
79 | logD("setProcessMemoryTrimLevel: url is empty");
80 | return;
81 | }
82 | logD("handleUrl:" + url);
83 | Uri data = Uri.parse(url);
84 | String schema = data.getScheme();
85 | if (!TextUtils.equals(SCHEME, schema.toLowerCase(Locale.ROOT))){
86 | logD("scheme illegal");
87 | return;
88 | }
89 | String action = data.getQueryParameter(KEY_ACTION);
90 | String fileName = data.getQueryParameter(KEY_FILE_NAME);
91 |
92 | if(TextUtils.equals(action, ACTION_READ_FILE)){
93 | if (mFileDataCache.containsKey(fileName)){
94 | logD("readFile: " + fileName + " from cache");
95 | param.setThrowable(new IllegalArgumentException(mFileDataCache.get(fileName)));
96 | readFileImpl(fileName);
97 | }else {
98 | param.setThrowable(new IllegalArgumentException(readFileImpl(fileName)));
99 | }
100 |
101 | }else if(TextUtils.equals(action, ACTION_WRITE_FILE)){
102 | String fileData = data.getQueryParameter(KEY_FILE_DATA);
103 | param.setResult(saveFileImpl(fileName, fileData));
104 |
105 | } else if(TextUtils.equals(action, ACTION_DELETE_FILE)){
106 | param.setResult(deleteFileImpl(fileName));
107 | }
108 | } else {
109 | logD("setProcessMemoryTrimLevel: is not our care url");
110 | }
111 | }));
112 | }
113 |
114 | public boolean saveFile(Context context, String fileName, String fileData){
115 | Uri.Builder builder = Uri.parse(SCHEME + "://hook").buildUpon();
116 | builder.appendQueryParameter(KEY_ACTION, ACTION_WRITE_FILE);
117 | builder.appendQueryParameter(KEY_FILE_NAME, fileName);
118 | builder.appendQueryParameter(KEY_FILE_DATA, fileData);
119 | return (boolean) mySetProcessMemoryTrimLevel(context, builder.toString());
120 | }
121 |
122 | public String readFile(Context context, String fileName){
123 | Uri.Builder builder = Uri.parse(SCHEME + "://hook").buildUpon();
124 | builder.appendQueryParameter(KEY_ACTION, ACTION_READ_FILE);
125 | builder.appendQueryParameter(KEY_FILE_NAME, fileName);
126 | String result = "";
127 | try {
128 | result = (String) mySetProcessMemoryTrimLevel(context, builder.toString());
129 | }catch (Exception e){/**/}
130 | return result;
131 | }
132 |
133 | public boolean deleteFile(Context context, String fileName){
134 | Uri.Builder builder = Uri.parse(SCHEME + "://hook").buildUpon();
135 | builder.appendQueryParameter(KEY_ACTION, ACTION_DELETE_FILE);
136 | builder.appendQueryParameter(KEY_FILE_NAME, fileName);
137 | return (boolean) mySetProcessMemoryTrimLevel(context, builder.toString());
138 | }
139 |
140 | private Object mySetProcessMemoryTrimLevel(Context context, String url){
141 | String result = "";
142 | if(context == null){
143 | return result;
144 | }
145 | try {
146 | ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
147 | return HiddenApiBypass.invoke(activityManager.getClass(), activityManager, "setProcessMemoryTrimLevel", url, HOOK_TAG, 1);
148 | }catch (Exception e){
149 | result = e.getCause() instanceof IllegalArgumentException ? e.getCause().getMessage() : "";
150 | }
151 | return TextUtils.isEmpty(result) ? false : result;
152 | }
153 |
154 | private boolean saveFileImpl(String fileName, String content) {
155 | if(mFileDataCache.containsKey(fileName) && TextUtils.equals(mFileDataCache.get(fileName), content)){
156 | logD("saveFileImpl: has same content, don't save " + fileName);
157 | return true;
158 | }
159 | File jsonFile = getFile(fileName);
160 | if (!jsonFile.exists()) {
161 | File jsonFileDirectory = new File(dataDir + "/");
162 | jsonFileDirectory.mkdirs();
163 | }
164 | logD("saveFile: " + content);
165 | try {
166 | FileOutputStream outputStream = new FileOutputStream(jsonFile);
167 | outputStream.write(content.getBytes());
168 | outputStream.close();
169 | mFileDataCache.put(fileName, content);
170 | return true;
171 | } catch (IOException e) {
172 | logE("saveFile: " + e.getCause());
173 | e.printStackTrace();
174 | }
175 | return false;
176 | }
177 |
178 | private boolean deleteFileImpl(String fileName){
179 | mFileDataCache.remove(fileName);
180 | File jsonFile = getFile(fileName);
181 | if (jsonFile.exists()) {
182 | return jsonFile.delete();
183 | }
184 | return false;
185 | }
186 |
187 | private String readFileImpl(String fileName){
188 | File jsonFile = getFile(fileName);
189 | String result = "";
190 | try {
191 | if (jsonFile.exists()) {
192 | ByteArrayOutputStream output = new ByteArrayOutputStream();
193 | byte[] buffer = new byte[4096];
194 | int n;
195 | InputStream input = new FileInputStream(jsonFile);
196 | while ((n = input.read(buffer)) != -1) {
197 | output.write(buffer, 0, n);
198 | }
199 | result = new String(output.toByteArray(), StandardCharsets.UTF_8);
200 | }
201 | } catch (Exception e) {
202 | logE("readFileImpl get "+ jsonFile.getName() + " err: " + e.getCause());
203 | }
204 | mFileDataCache.put(fileName, result);
205 | logD("readFileImpl get "+ jsonFile.getName() + " success: " + result);
206 | return result;
207 | }
208 |
209 | private File getFile(String fileName){
210 | return new File(dataDir + "/" + fileName);
211 | }
212 |
213 | private void logD(String message){
214 | Log.d("Xposed", "FileUtils " + message);
215 | }
216 |
217 | private void logE(String message){
218 | Log.e("Xposed", "FileUtils " + message);
219 | }
220 |
221 | }
222 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xiaoer/watermark/ui/edit/EditConfigActivity.java:
--------------------------------------------------------------------------------
1 | package com.xiaoer.watermark.ui.edit;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.text.Editable;
8 | import android.text.TextUtils;
9 | import android.text.TextWatcher;
10 | import android.view.Menu;
11 | import android.view.MenuItem;
12 | import android.view.MotionEvent;
13 | import android.view.View;
14 | import android.view.inputmethod.InputMethodManager;
15 | import android.widget.EditText;
16 | import android.widget.FrameLayout;
17 | import android.widget.SeekBar;
18 | import android.widget.TextView;
19 |
20 | import androidx.activity.result.ActivityResultLauncher;
21 | import androidx.activity.result.contract.ActivityResultContracts;
22 | import androidx.appcompat.app.AppCompatActivity;
23 | import androidx.appcompat.widget.AppCompatSeekBar;
24 |
25 | import com.flask.colorpicker.ColorPickerView;
26 | import com.flask.colorpicker.builder.ColorPickerDialogBuilder;
27 | import com.google.android.material.button.MaterialButton;
28 | import com.google.android.material.card.MaterialCardView;
29 | import com.google.android.material.dialog.MaterialAlertDialogBuilder;
30 | import com.google.android.material.switchmaterial.SwitchMaterial;
31 | import com.google.android.material.textfield.TextInputEditText;
32 | import com.xiaoer.watermark.R;
33 | import com.xiaoer.watermark.bean.WaterMarkConfig;
34 | import com.xiaoer.watermark.hook.ConfigHelper;
35 | import com.xiaoer.watermark.ui.WaterMarkView;
36 | import com.xiaoer.watermark.ui.WatermarkDrawable;
37 |
38 | public class EditConfigActivity extends AppCompatActivity implements View.OnClickListener {
39 | public static final String REQUEST_CONFIG_KEY = "request_waterMarkConfig";
40 |
41 | private WaterMarkConfig mWaterMarkConfig;
42 | private SwitchMaterial mSmState;
43 | private FrameLayout mFlShow;
44 | private TextInputEditText mEtContent;
45 | private AppCompatSeekBar mAsbRotation;
46 | private AppCompatSeekBar mAsbTextSize;
47 |
48 | private ActivityResultLauncher mResultLauncher;
49 |
50 | private boolean shouldReload = false;
51 |
52 | public static Intent getStartIntent(Context context){
53 | return new Intent(context, EditConfigActivity.class);
54 | }
55 |
56 | public static Intent getStartIntentWithConfig(Context context, WaterMarkConfig waterMarkConfig){
57 | Intent startIntent = getStartIntent(context);
58 | startIntent.putExtra(REQUEST_CONFIG_KEY, waterMarkConfig);
59 | return startIntent;
60 | }
61 |
62 | @Override
63 | protected void onCreate(Bundle savedInstanceState) {
64 | super.onCreate(savedInstanceState);
65 | setContentView(R.layout.activity_edit_config);
66 |
67 | mResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
68 | if (result.getResultCode() == RESULT_OK && result.getData() != null) {
69 | mWaterMarkConfig = (WaterMarkConfig) result.getData().getSerializableExtra("result");
70 | shouldReload = true;
71 | }
72 | });
73 | initData();
74 | initView();
75 | updateView();
76 | }
77 |
78 | private void initData() {
79 | Intent intent = getIntent();
80 | if(intent != null && intent.getSerializableExtra(REQUEST_CONFIG_KEY) != null){
81 | mWaterMarkConfig = (WaterMarkConfig) intent.getSerializableExtra(REQUEST_CONFIG_KEY);
82 | }else {
83 | mWaterMarkConfig = new WaterMarkConfig();
84 | }
85 | }
86 |
87 | @Override
88 | public boolean onCreateOptionsMenu(Menu menu) {
89 | MenuItem save = menu.add("");
90 | save.setIcon(R.drawable.baseline_save_24);
91 | save.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
92 | save.setOnMenuItemClickListener(item -> {
93 | boolean success = ConfigHelper.saveWaterMarkConfig(EditConfigActivity.this, mWaterMarkConfig);
94 | if(success){
95 | finishEdit(true);
96 | }
97 | return true;
98 | });
99 | return super.onCreateOptionsMenu(menu);
100 | }
101 |
102 | private void initView() {
103 | mSmState = findViewById(R.id.sm_state);
104 | MaterialCardView mcvStatus = findViewById(R.id.module_status_card);
105 | TextView tvStatus = findViewById(R.id.module_status_text);
106 | mFlShow = findViewById(R.id.fl_show);
107 | mEtContent = findViewById(R.id.et_content);
108 | MaterialButton mbColor = findViewById(R.id.mb_color);
109 | MaterialButton mbAppList = findViewById(R.id.mb_appList);
110 | mAsbRotation = findViewById(R.id.asb_rotation);
111 | mAsbTextSize = findViewById(R.id.asb_text_size);
112 |
113 | mAsbRotation.setMax(360);
114 | mAsbTextSize.setMax(100);
115 | mAsbTextSize.setMin(1);
116 | mbColor.setOnClickListener(this);
117 | mbAppList.setOnClickListener(this);
118 | if(ConfigHelper.isModuleActivated()){
119 | mcvStatus.setCardBackgroundColor(getColor(R.color.purple_500));
120 | tvStatus.setText("启用模块");
121 | mSmState.setEnabled(true);
122 | }else {
123 | mcvStatus.setCardBackgroundColor(getColor(R.color.red_500));
124 | tvStatus.setText("模块未成功激活");
125 | mSmState.setEnabled(false);
126 | }
127 | mSmState.setOnCheckedChangeListener((buttonView, isChecked) -> mWaterMarkConfig.setOpen(isChecked));
128 | mEtContent.addTextChangedListener(new TextWatcher() {
129 | @Override
130 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {
131 |
132 | }
133 |
134 | @Override
135 | public void onTextChanged(CharSequence s, int start, int before, int count) {
136 |
137 | }
138 |
139 | @Override
140 | public void afterTextChanged(Editable s) {
141 | if(s != null && !TextUtils.equals(s.toString(), mWaterMarkConfig.getContent())){
142 | mWaterMarkConfig.setContent(TextUtils.isEmpty(s.toString()) ? "waterMark" : s.toString());
143 | updateWaterView();
144 | }
145 | }
146 | });
147 | mAsbRotation.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
148 | @Override
149 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
150 | mWaterMarkConfig.setRotation(-progress);
151 | updateWaterView();
152 | }
153 |
154 | @Override
155 | public void onStartTrackingTouch(SeekBar seekBar) {
156 |
157 | }
158 |
159 | @Override
160 | public void onStopTrackingTouch(SeekBar seekBar) {
161 |
162 | }
163 | });
164 | mAsbTextSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
165 | @Override
166 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
167 | mWaterMarkConfig.setTextSize(progress);
168 | updateWaterView();
169 | }
170 |
171 | @Override
172 | public void onStartTrackingTouch(SeekBar seekBar) {
173 |
174 | }
175 |
176 | @Override
177 | public void onStopTrackingTouch(SeekBar seekBar) {
178 |
179 | }
180 | });
181 |
182 | }
183 |
184 | private void updateWaterView() {
185 | WatermarkDrawable drawable = new WatermarkDrawable(EditConfigActivity.this, mWaterMarkConfig);
186 | WaterMarkView waterMarkView = new WaterMarkView(EditConfigActivity.this, drawable);
187 | mFlShow.removeAllViews();
188 | mFlShow.addView(waterMarkView);
189 | }
190 |
191 | private void updateView() {
192 | if(mWaterMarkConfig == null){
193 | return;
194 | }
195 | mSmState.setChecked(mWaterMarkConfig.isOpen());
196 | mEtContent.setText(mWaterMarkConfig.getContent());
197 | updateWaterView();
198 | mAsbRotation.setProgress((int) Math.abs(mWaterMarkConfig.getRotation()));
199 | mAsbTextSize.setProgress(Math.abs(mWaterMarkConfig.getTextSize()));
200 |
201 | }
202 |
203 |
204 | @Override
205 | public void onBackPressed() {
206 | if(!shouldReload){
207 | MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(EditConfigActivity.this);
208 | materialAlertDialogBuilder.setTitle("退出而不保存");
209 | materialAlertDialogBuilder.setMessage("所有变更将会丢失");
210 | materialAlertDialogBuilder.setPositiveButton("确认", (dialog, which) -> {
211 | dialog.dismiss();
212 | finishEdit(false);
213 | });
214 | materialAlertDialogBuilder.setNegativeButton("取消", null);
215 | materialAlertDialogBuilder.show();
216 | }else {
217 | finishEdit(true);
218 | }
219 | }
220 |
221 | public void finishEdit(boolean hasChange){
222 | if (shouldReload || hasChange){
223 | setResult(RESULT_OK);
224 | }
225 | finish();
226 | }
227 |
228 | @Override
229 | public boolean dispatchTouchEvent(MotionEvent ev) {
230 | if (ev.getAction() == MotionEvent.ACTION_DOWN) {
231 | // 获得当前得到焦点的View,一般情况下就是EditText(特殊情况就是轨迹求或者实体案件会移动焦点)
232 | View v = getCurrentFocus();
233 | View currentFocus = getCurrentFocus();
234 | if (isShouldHideInput(v, ev)) {
235 | hideInputMethod(this, v);
236 | if (currentFocus != null) {
237 | // 点击EditText外的其他区域。 关闭键盘 取消光标显示
238 | if (currentFocus instanceof EditText) {
239 | currentFocus.clearFocus();
240 | }
241 | }
242 | } else {
243 | // 点击EditText的事件,不需要隐藏键盘,需要显示光标。
244 | if (currentFocus != null) {
245 | if (currentFocus instanceof EditText) {
246 | currentFocus.requestFocus();
247 | }
248 | }
249 | }
250 | }
251 | return super.dispatchTouchEvent(ev);
252 |
253 | }
254 |
255 | private boolean isShouldHideInput(View v, MotionEvent event) {
256 | if ((v instanceof EditText)) {
257 | int[] l = {0, 0};
258 | v.getLocationInWindow(l);
259 | int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
260 | return !(event.getX() > left) || !(event.getX() < right) || !(event.getY() > top) || !(event.getY() < bottom);
261 | }
262 | // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditView上,和用户用轨迹球选择其他的焦点
263 | return false;
264 | }
265 |
266 | public void hideInputMethod(Activity activity, View view) {
267 | InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
268 | if (imm != null) {
269 | imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
270 | }
271 | }
272 |
273 | @Override
274 | public void onClick(View v) {
275 | int id = v.getId();
276 | if (id == R.id.mb_color){
277 | ColorPickerDialogBuilder
278 | .with(EditConfigActivity.this)
279 | .setTitle("选择水印颜色")
280 | .initialColor(mWaterMarkConfig.getTextColor())
281 | .wheelType(ColorPickerView.WHEEL_TYPE.FLOWER)
282 | .density(12)
283 | .setPositiveButton("确认", (dialog, selectedColor, allColors) -> {
284 | mWaterMarkConfig.setTextColor(selectedColor);
285 | updateWaterView();
286 | dialog.dismiss();
287 | })
288 | .setNegativeButton("取消", null)
289 | .build()
290 | .show();
291 | }else if(id == R.id.mb_appList) {
292 | mResultLauncher.launch(SelectPackageActivity.getStartIntentWithConfig(EditConfigActivity.this, mWaterMarkConfig));
293 | }
294 | }
295 | }
--------------------------------------------------------------------------------