diff --git a/app/build.gradle b/app/build.gradle index 95fbcce..19b33a6 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -61,12 +61,12 @@ this.afterEvaluate { android { namespace 'com.pic.catcher' - compileSdk 35 + compileSdk COMPILE_SDK_VERSION.toInteger() defaultConfig { applicationId "com.pic.catcher" minSdk 24 - targetSdk 35 + targetSdk TARGET_SDK_VERSION.toInteger() versionCode 1 versionName "1.0-gaoji" @@ -85,7 +85,7 @@ android { // } signingConfigs { alpha { - storeFile file("${rootDir}/app/key-store-test.jks") + storeFile file("${rootDir}/keys/key-store-test.jks") storePassword "123456" keyAlias "piccatch" keyPassword "123456" @@ -94,8 +94,8 @@ android { buildTypes { debug { debuggable true - minifyEnabled true - shrinkResources true + minifyEnabled false + shrinkResources false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro','proguard-rules-debug.pro' signingConfig signingConfigs.alpha } diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index fa17412..8e6fd2b 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -30,20 +30,17 @@ #} -keepclassmembers class * extends com.pic.catcher.base.BaseFragment { - (); + (); } -keepclassmembers class * extends com.pic.catcher.base.BaseViewModel { (); } -keepclassmembers class * extends com.pic.catcher.base.BaseFragment { - (*); + (); } -keepclassmembers class * extends com.pic.catcher.base.BaseViewModel { - (*); + (); } -keepclassmembers class * extends com.lu.lposed.plugin.IPlugin { (*); } --keepclassmembers class * extends com.lu.lposed.plugin.IPlugin { - (); -} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d9aed44..ff2e889 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -13,8 +13,7 @@ android:networkSecurityConfig="@xml/network_security_config" android:roundIcon="@mipmap/ic_launcher" android:supportsRtl="true" - android:theme="@style/Theme.PicCatcher" - tools:targetApi="31"> + android:theme="@style/Theme.PicCatcher"> diff --git a/app/src/main/java/com/pic/catcher/MainHook.java b/app/src/main/java/com/pic/catcher/MainHook.java index e5669b2..93aa482 100644 --- a/app/src/main/java/com/pic/catcher/MainHook.java +++ b/app/src/main/java/com/pic/catcher/MainHook.java @@ -16,8 +16,10 @@ import com.lu.magic.util.log.SimpleLogger; import com.pic.catcher.plugin.BitmapCatcherPlugin; import com.pic.catcher.plugin.GlideCatcherPlugin; +import com.pic.catcher.plugin.OKHttpPlugin; import com.pic.catcher.plugin.WebViewCatcherPlugin; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -87,7 +89,11 @@ public void onLog(int level, @NonNull Object[] objects) { return (short) 0; } if (BuildConfig.DEBUG) { - LogUtil.w("setOnErrorReturnFallback", throwable); + if (throwable instanceof InvocationTargetException) { + LogUtil.w("setOnErrorReturnFallback", ((InvocationTargetException) throwable).getTargetException()); + } else { + LogUtil.w("setOnErrorReturnFallback2", throwable); + } } return null; }); @@ -119,18 +125,18 @@ protected void afterHookedMethod(MethodHookParam param) throws Throwable { // } // ); // - unhook = XposedHelpers2.findAndHookMethod( - Instrumentation.class.getName(), - lpparam.classLoader, - "callApplicationOnCreate", - Application.class.getName(), - new XC_MethodHook2() { - @Override - protected void afterHookedMethod(MethodHookParam param) throws Throwable { - initPlugin((Context) param.args[0], lpparam); - } - } - ); +// unhook = XposedHelpers2.findAndHookMethod( +// Instrumentation.class.getName(), +// lpparam.classLoader, +// "callApplicationOnCreate", +// Application.class.getName(), +// new XC_MethodHook2() { +// @Override +// protected void afterHookedMethod(MethodHookParam param) throws Throwable { +// initPlugin((Context) param.args[0], lpparam); +// } +// } +// ); initUnHookList.add(unhook); // // XposedHelpers2.findAndHookMethod( @@ -182,9 +188,10 @@ private void initSelfPlugins(Context context, XC_LoadPackage.LoadPackageParam lp private void initTargetPlugins(Context context, XC_LoadPackage.LoadPackageParam lpparam) { //目前生成的plugin都是单例的 PluginRegistry.register( - BitmapCatcherPlugin.class, - GlideCatcherPlugin.class, - WebViewCatcherPlugin.class +// BitmapCatcherPlugin.class, +// GlideCatcherPlugin.class, +// WebViewCatcherPlugin.class + OKHttpPlugin.class ).handleHooks(context, lpparam); diff --git a/app/src/main/java/com/pic/catcher/plugin/OKHttpPlugin.java b/app/src/main/java/com/pic/catcher/plugin/OKHttpPlugin.java new file mode 100644 index 0000000..5c5802a --- /dev/null +++ b/app/src/main/java/com/pic/catcher/plugin/OKHttpPlugin.java @@ -0,0 +1,135 @@ +package com.pic.catcher.plugin; + +import android.content.Context; +import android.text.TextUtils; +import android.webkit.MimeTypeMap; + +import com.lu.lposed.api2.XC_MethodHook2; +import com.lu.lposed.api2.XposedHelpers2; +import com.lu.lposed.plugin.IPlugin; +import com.lu.magic.util.AppUtil; +import com.lu.magic.util.log.LogUtil; +import com.pic.catcher.ClazzN; +import com.pic.catcher.util.Regexs; + +import java.io.ByteArrayOutputStream; +import java.lang.reflect.Method; +import java.util.Arrays; + +import de.robv.android.xposed.callbacks.XC_LoadPackage; + +/** + * @author Lu + * @date 2024/10/26 23:16 + * @description + */ +public class OKHttpPlugin implements IPlugin { + @Override + public void handleHook(Context context, XC_LoadPackage.LoadPackageParam loadPackageParam) { + handleHookOkHttp3(context, loadPackageParam); +// handleHookAndroidOkHttp(context, loadPackageParam); + } + + private void handleHookAndroidOkHttp(Context context, XC_LoadPackage.LoadPackageParam loadPackageParam) { + XposedHelpers2.findAndHookMethod( + ClazzN.from("com.android.okhttp.internal.http.HttpEngine"), + "readResponse", + new XC_MethodHook2() { + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + Object response = XposedHelpers2.getObjectField(param.thisObject, "userResponse"); + + LogUtil.d("response", response); + + String contentType = (String) XposedHelpers2.callMethod(response, "header", "Content-Type"); + if (TextUtils.isEmpty(contentType)) { + LogUtil.d("content-type is empty"); + return; + } + String guessFileEx = MimeTypeMap.getSingleton().getExtensionFromMimeType(contentType); + if (TextUtils.isEmpty(guessFileEx) || !Regexs.PIC_EXT.matcher(guessFileEx).find()) { + //不是图片 + return; + } + Object body = XposedHelpers2.callMethod(response, "body"); + LogUtil.d("body", body); + if (body == null) { + return; + } + //com.android.okhttp.internal.http.Http1xStream$FixedLengthSource + Object source = XposedHelpers2.callMethod(body, "source"); + LogUtil.d("bufferedSource", source); + if (source == null) { + return; + } + //读取二进制 + Object bytes = XposedHelpers2.callMethod(source, "readByteArray"); +// Object buffer = XposedHelpers2.getObjectField(source, "buffer"); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + outputStream.write((byte[]) bytes); + Object sink = XposedHelpers2.callStaticMethod(ClazzN.from("com.android.okhttp.okio.Okio"), "sink", outputStream); + Object buffer = XposedHelpers2.callMethod(ClazzN.from("com.android.okhttp.okio.Okio"), "buffer", sink); + XposedHelpers2.setObjectField(body, "buffer", buffer); + + //com.android.okhttp.internal.http.Http1xStream$FixedLengthSource +// Object sourceField = XposedHelpers2.getObjectField(source, "source"); +// XposedHelpers2.callMethod(buffer, "read", bytes); + //读完就废了,所以复制一个给原先的结果 + +// LogUtil.d("readByteArray is ok", bytes + "", sourceField); + if (bytes != null) { + LogUtil.d("readByteArray is bytes. start download"); + PicExportManager.getInstance().exportByteArray((byte[]) bytes, guessFileEx); + } + } + } + ); + + } + + private void handleHookOkHttp3(Context context, XC_LoadPackage.LoadPackageParam loadPackageParam) { + ClassLoader clazzLoader = AppUtil.getClassLoader(); + LogUtil.d("OKHttpPlugin", "handleHook", clazzLoader); + Class realCallClazz = ClazzN.from("okhttp3.RealCall", clazzLoader); + if (realCallClazz == null) { + LogUtil.d("can not find RealCall class"); + return; + } + XposedHelpers2.findAndHookMethod( + realCallClazz, +// "execute", + "getResponseWithInterceptorChain", + new XC_MethodHook2() { + + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + Object response = param.getResult(); + String contentType = (String) XposedHelpers2.callMethod(response, "header", "Content-Type"); + if (TextUtils.isEmpty(contentType)) { + LogUtil.d("content-type is empty"); + return; + } + String guessFileEx = MimeTypeMap.getSingleton().getExtensionFromMimeType(contentType); + if (TextUtils.isEmpty(guessFileEx) || !Regexs.PIC_EXT.matcher(guessFileEx).find()) { + //不是图片 + return; + } + + // 制造一个新的body,不影响原始数据读写 + Object response2 = XposedHelpers2.callMethod(response, "peekBody", Long.MAX_VALUE); + if (response2 == null) { + LogUtil.d("response2 is null"); + return; + } + Object bytes = XposedHelpers2.callMethod(response2, "bytes"); + if (bytes instanceof byte[]) { + LogUtil.d("readByteArray is bytes. start download"); + PicExportManager.getInstance().exportByteArray((byte[]) bytes, guessFileEx); + } + } + } + ); + + } +} diff --git a/app/src/main/java/com/pic/catcher/plugin/PicExportManager.java b/app/src/main/java/com/pic/catcher/plugin/PicExportManager.java index f957001..df0c9a4 100644 --- a/app/src/main/java/com/pic/catcher/plugin/PicExportManager.java +++ b/app/src/main/java/com/pic/catcher/plugin/PicExportManager.java @@ -168,6 +168,7 @@ public void exportByteArray(final byte[] dataBytes, String lastName) { final String finalLastName = lastName; runOnIo(() -> { if (dataBytes == null || dataBytes.length == 0) { + LogUtil.d("exportByteArray: dataBytes is empty"); return; } FileOutputStream fileOutputStream = null; @@ -175,6 +176,7 @@ public void exportByteArray(final byte[] dataBytes, String lastName) { String fileName = Md5Util.get(dataBytes) + finalLastName; File file = new File(this.exportDir, fileName); if (file.exists()) { + LogUtil.d("exportByteArray: file already exists:", file); return; } this.exportDir.mkdirs(); @@ -182,7 +184,8 @@ public void exportByteArray(final byte[] dataBytes, String lastName) { IOUtil.writeByByte(dataBytes, fileOutputStream); LogUtil.d("exportByteArray: ", file); } catch (Throwable th) { - th.printStackTrace(); +// th.printStackTrace(); + LogUtil.d(th); } finally { IOUtil.closeQuietly(fileOutputStream); } diff --git a/app/src/main/java/com/pic/catcher/plugin/X5WebViewCatcherPlugin.java b/app/src/main/java/com/pic/catcher/plugin/X5WebViewCatcherPlugin.java new file mode 100644 index 0000000..c389b01 --- /dev/null +++ b/app/src/main/java/com/pic/catcher/plugin/X5WebViewCatcherPlugin.java @@ -0,0 +1,44 @@ +package com.pic.catcher.plugin; + +import android.content.Context; +import android.webkit.WebView; + +import com.lu.lposed.api2.XC_MethodHook2; +import com.lu.lposed.api2.XposedHelpers2; +import com.lu.lposed.plugin.IPlugin; +import com.lu.magic.util.log.LogUtil; +import com.pic.catcher.ClazzN; + +import de.robv.android.xposed.callbacks.XC_LoadPackage; + +/** + * @author Lu + * @date 2024/10/13 14:48 + * @description x5webview 网页图片加载获取 + */ +public class X5WebViewCatcherPlugin implements IPlugin { + + @Override + public void handleHook(Context context, XC_LoadPackage.LoadPackageParam loadPackageParam) { + Class webViewClientClazz = ClazzN.from("com.tencent.smtt.sdk.WebViewClient"); + Class webViewClazz = ClazzN.from("com.tencent.smtt.sdk.WebView"); + if (webViewClientClazz == null || webViewClazz == null) { + return; + } + XposedHelpers2.findAndHookMethod( + webViewClientClazz, + "onLoadResource", + webViewClazz, + String.class, + new XC_MethodHook2() { + @Override + protected void afterHookedMethod(MethodHookParam param) throws Throwable { + WebView webView = (WebView) param.args[0]; + String url = (String) param.args[1]; + LogUtil.d("WebViewClient.onLoadResource", "url=" + url); + PicExportManager.getInstance().exportUrlIfNeed(url); + } + } + ); + } +} diff --git a/app/src/main/java/com/pic/catcher/util/ext/AnyX.kt b/app/src/main/java/com/pic/catcher/util/ext/AnyX.kt index 525f53c..f4c799c 100644 --- a/app/src/main/java/com/pic/catcher/util/ext/AnyX.kt +++ b/app/src/main/java/com/pic/catcher/util/ext/AnyX.kt @@ -57,7 +57,7 @@ fun TextView.setTextColorTheme(color: Int) { } -inline fun T?.takeNotNull(fallback: T): T { +fun T?.takeNotNull(fallback: T): T { if (this == null) { return fallback } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 435cd5d..4ab1489 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,5 +1,5 @@ - PicCatcher + 图片捕手 App图片抓取器 模块未激活 模块已激活 diff --git a/build.gradle b/build.gradle index 4b62788..5d375a0 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,7 @@ buildscript { } plugins { - id 'com.android.application' version '8.5.2' apply false - id 'com.android.library' version '8.5.2' apply false + id 'com.android.application' version '8.6.0' apply false + id 'com.android.library' version '8.6.0' apply false id 'org.jetbrains.kotlin.android' version '2.0.20' apply false } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 532582a..9f71aa8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -21,5 +21,10 @@ kotlin.code.style=official # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library android.nonTransitiveRClass=true -#?debug apk??????? -android.injected.testOnly = false \ No newline at end of file +#设置debug apk也可以点击直接安装 +android.injected.testOnly=false + +TARGET_SDK_VERSION=35 +COMPILE_SDK_VERSION=35 + +#org.gradle.java.home=C\:\\Programing\\Android\\android-studio\\jbr \ No newline at end of file diff --git a/app/key-store-test.jks b/keys/key-store-test.jks similarity index 100% rename from app/key-store-test.jks rename to keys/key-store-test.jks diff --git a/props.gradle b/props.gradle index 262e18e..3ed1179 100644 --- a/props.gradle +++ b/props.gradle @@ -28,11 +28,9 @@ ext { 'com.github.Mingyueyixi.frame-base-utils:core' : 'com.github.Mingyueyixi.frame-base-utils:core:40657f21dc', -// 'com.github.Mingyueyixi:frame-ui' : 'com.github.Mingyueyixi:frame-ui:main-SNAPSHOT', -// 'com.github.Mingyueyixi:frame-ui' : 'com.github.Mingyueyixi:frame-ui:v1.0.0-alpha.2', -// 'com.github.Mingyueyixi.frame-ui:ui-all' : 'com.github.Mingyueyixi.frame-ui:ui-all:8db89324ba', -// 'com.github.Mingyueyixi.frame-ui:ui-material' : 'com.github.Mingyueyixi.frame-ui:ui-material:8db89324ba', -// 'com.github.Mingyueyixi.frame-ui:ui-base' : 'com.github.Mingyueyixi.frame-ui:ui-base:8db89324ba', +// 'com.github.Mingyueyixi.frame-ui:ui-all' : 'com.github.Mingyueyixi.frame-ui:ui-all:332536884f', + 'com.github.Mingyueyixi.frame-ui:ui-material' : 'com.github.Mingyueyixi.frame-ui:ui-material:332536884f', +// 'com.github.Mingyueyixi.frame-ui:ui-base' : 'com.github.Mingyueyixi.frame-ui:ui-base:332536884f', 'com.github.Mingyueyixi.frame-ui:ui-appcompat' : 'com.github.Mingyueyixi.frame-ui:ui-appcompat:332536884f', 'com.github.Mingyueyixi:frame-multi-preference' : 'com.github.Mingyueyixi:frame-multi-preference:main-SNAPSHOT', diff --git a/settings.gradle b/settings.gradle index 8cf7a0f..13902a9 100644 --- a/settings.gradle +++ b/settings.gradle @@ -4,12 +4,13 @@ pluginManagement { // allowInsecureProtocol = true // url "http://127.0.0.1:10072" // } - maven { url 'https://jitpack.io/' } maven { url 'https://mirrors.cloud.tencent.com/nexus/repository/maven-public' } maven { url 'https://repo.huaweicloud.com/repository/maven' } + maven { url "https://maven.aliyun.com/repository/public" } + maven { url 'https://jitpack.io/' } + //central有的,public聚合仓不一定有,奇葩 maven { url 'https://maven.aliyun.com/repository/central' } - maven { url "https://maven.aliyun.com/repository/public" } maven { url "https://maven.aliyun.com/repository/google" } maven { url "https://maven.aliyun.com/repository/gradle-plugin" } @@ -26,12 +27,13 @@ dependencyResolutionManagement { // url "http://127.0.0.1:10072" // } - maven { url 'https://jitpack.io/' } maven { url 'https://mirrors.cloud.tencent.com/nexus/repository/maven-public' } maven { url 'https://repo.huaweicloud.com/repository/maven' } + maven { url "https://maven.aliyun.com/repository/public" } + maven { url 'https://jitpack.io/' } + //central有的,public聚合仓不一定有,奇葩 maven { url 'https://maven.aliyun.com/repository/central' } - maven { url "https://maven.aliyun.com/repository/public" } maven { url "https://maven.aliyun.com/repository/google" } maven { url "https://maven.aliyun.com/repository/gradle-plugin" } @@ -40,4 +42,5 @@ dependencyResolutionManagement { } } rootProject.name = "PicCatcher" -include ':app' \ No newline at end of file +include ':app' +include ':testapp' diff --git a/testapp/.gitignore b/testapp/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/testapp/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/testapp/build.gradle b/testapp/build.gradle new file mode 100644 index 0000000..b4f1859 --- /dev/null +++ b/testapp/build.gradle @@ -0,0 +1,80 @@ +import org.json.JSONObject + +import java.text.SimpleDateFormat + +plugins { + id 'com.android.application' + id 'org.jetbrains.kotlin.android' +} +apply { + from rootProject.file('props.gradle') +} + +android { + namespace 'com.pic.testapp' + compileSdk COMPILE_SDK_VERSION.toInteger() + + defaultConfig { + applicationId "com.pic.testapp" + minSdk 23 + targetSdk TARGET_SDK_VERSION.toInteger() + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + signingConfigs { + alpha { + storeFile file("${rootDir}/keys/key-store-test.jks") + storePassword "123456" + keyAlias "piccatch" + keyPassword "123456" + } + } + buildTypes { + debug { + debuggable true + minifyEnabled false + shrinkResources false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro','proguard-rules-debug.pro' + signingConfig signingConfigs.alpha + } + release { + debuggable false + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + signingConfig signingConfigs.alpha + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = '1.8' + } + buildFeatures { + viewBinding true + } +} + +dependencies { + implementation 'androidx.core:core-ktx:1.10.1' + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'com.google.android.material:material:1.10.0' + // Flex布局依赖,可配合RecyclerView也可以单独使用 + // https://mvnrepository.com/artifact/com.google.android.flexbox/flexbox + implementation 'com.google.android.flexbox:flexbox:3.0.0' + implementation deps['com.github.Mingyueyixi.frame-ui:ui-material'] + api 'com.tencent.tbs:tbssdk:44286' + implementation 'com.squareup.okhttp3:okhttp:3.14.7' + implementation 'com.squareup.okio:okio:1.17.5' + implementation(deps['com.github.Mingyueyixi.frame-base-utils:base']) + +// implementation('com.github.Mingyueyixi.frame-base-utils:core') + +// testImplementation 'junit:junit:4.14-SNAPSHOT' +// androidTestImplementation 'androidx.test.ext:junit:1.1.5' +// androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' +} \ No newline at end of file diff --git a/testapp/proguard-rules.pro b/testapp/proguard-rules.pro new file mode 100644 index 0000000..107b7ee --- /dev/null +++ b/testapp/proguard-rules.pro @@ -0,0 +1,32 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile + +-dontwarn dalvik.** +-dontwarn com.tencent.smtt.** + +-keep class com.tencent.smtt.** { + *; +} + +-keep class com.tencent.tbs.** { + *; +} \ No newline at end of file diff --git a/testapp/src/androidTest/java/com/pic/testapp/ExampleInstrumentedTest.kt b/testapp/src/androidTest/java/com/pic/testapp/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..af142c8 --- /dev/null +++ b/testapp/src/androidTest/java/com/pic/testapp/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.pic.testapp + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.pic.testapp", appContext.packageName) + } +} \ No newline at end of file diff --git a/testapp/src/main/AndroidManifest.xml b/testapp/src/main/AndroidManifest.xml new file mode 100644 index 0000000..f9e2978 --- /dev/null +++ b/testapp/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testapp/src/main/java/com/pic/testapp/App.java b/testapp/src/main/java/com/pic/testapp/App.java new file mode 100644 index 0000000..44c84e5 --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/App.java @@ -0,0 +1,25 @@ +package com.pic.testapp; + +import android.app.Application; +import android.content.Context; + +/** + * @author Lu + * @date 2024/10/26 20:11 + * @description + */ +public class App extends Application { + private static App instance; + + + public static App getInstance() { + return instance; + } + + @Override + protected void attachBaseContext(Context base) { + instance = this; + super.attachBaseContext(base); + } + +} diff --git a/testapp/src/main/java/com/pic/testapp/ItemBean.kt b/testapp/src/main/java/com/pic/testapp/ItemBean.kt new file mode 100644 index 0000000..8648a9d --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/ItemBean.kt @@ -0,0 +1,8 @@ +package com.pic.testapp + +/** + * @author Lu + * @date 2024/10/26 19:24 + * @description + */ +class ItemBean(val title: String, val action: Any) \ No newline at end of file diff --git a/testapp/src/main/java/com/pic/testapp/LauncherUiActivity.java b/testapp/src/main/java/com/pic/testapp/LauncherUiActivity.java new file mode 100644 index 0000000..2cba44e --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/LauncherUiActivity.java @@ -0,0 +1,23 @@ +package com.pic.testapp; + +import android.os.Bundle; + +import androidx.annotation.Nullable; + +import com.pic.testapp.base.BaseActivity; + +import okhttp3.Response; +import okio.Buffer; + +/** + * @author Lu + * @date 2024/10/26 12:57 + * @description + */ +public class LauncherUiActivity extends BaseActivity { + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + addFragment(new MainFragment()); + } +} diff --git a/testapp/src/main/java/com/pic/testapp/LocalStorage.java b/testapp/src/main/java/com/pic/testapp/LocalStorage.java new file mode 100644 index 0000000..2720fcf --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/LocalStorage.java @@ -0,0 +1,20 @@ +package com.pic.testapp; + +import android.content.Context; +import android.content.SharedPreferences; + +/** + * @author Lu + * @date 2024/10/26 20:24 + * @description + */ +public class LocalStorage { + public static SharedPreferences getDefault() { + return App.getInstance().getSharedPreferences("appDefaultConfig", Context.MODE_PRIVATE); + } + + public interface Key { + String X5_WEB_VIEW_LAST_URL = "x5WebViewLastUrl"; + String WEB_VIEW_LAST_URL = "WebViewLastUrl"; + } +} diff --git a/testapp/src/main/java/com/pic/testapp/MainFragment.kt b/testapp/src/main/java/com/pic/testapp/MainFragment.kt new file mode 100644 index 0000000..114c6eb --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/MainFragment.kt @@ -0,0 +1,84 @@ +package com.pic.testapp + +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.Toast +import com.google.android.flexbox.FlexDirection +import com.google.android.flexbox.FlexWrap +import com.google.android.flexbox.FlexboxLayoutManager +import com.lu.magic.ui.recycler.MultiAdapter +import com.lu.magic.ui.recycler.MultiViewHolder +import com.lu.magic.ui.recycler.SimpleItemType +import com.pic.testapp.action.Action +import com.pic.testapp.action.LoadBitmapAction +import com.pic.testapp.action.LoadHttpPicAction +import com.pic.testapp.base.BaseFragment +import com.pic.testapp.base.BindingFragment +import com.pic.testapp.databinding.FragMainLayoutBinding +import com.pic.testapp.databinding.ItemTextInlineBlockBinding + +class MainFragment : BindingFragment() { + + private lateinit var mAdapter: MultiAdapter + + override fun onCreateBinding(inflater: LayoutInflater, container: ViewGroup?): FragMainLayoutBinding { + return FragMainLayoutBinding.inflate(inflater, container, false) + } + + override fun initView() { + mBinding.mainRecyclerView.layoutManager = object : FlexboxLayoutManager(context, FlexDirection.ROW, FlexWrap.WRAP) { + override fun canScrollVertically(): Boolean { + return true + } + } + + mBinding.mainRecyclerView.adapter = MultiAdapter().addItemType(object : SimpleItemType() { + override fun createViewHolder(adapter: MultiAdapter, parent: ViewGroup, viewType: Int): MultiViewHolder { + return ItemBindingViewHolder(ItemTextInlineBlockBinding.inflate(layoutInflater, parent, false)) + } + }).also { + mAdapter = it + } + } + + override fun initData() { + mAdapter.setData( + listOf( + ItemBean("显示网络图片", LoadHttpPicAction()), + ItemBean("loadBitmap", LoadBitmapAction()), + ItemBean("webview", WebViewFragment::class.java), + ItemBean("x5Webview", X5WebViewFragment::class.java), + ) + ) + } + + + inner class ItemBindingViewHolder(val itemBinding: ItemTextInlineBlockBinding) : MultiViewHolder(itemBinding.root) { + + override fun onBindView(adapter: MultiAdapter, itemModel: ItemBean, position: Int) { + itemBinding.itemTextContent.setText(itemModel.title) + itemBinding.itemTextContent.setOnClickListener { + if (itemModel.action is Class<*>) { + if (BaseFragment::class.java.isAssignableFrom(itemModel.action)) { + //传入的是BaseFragment子类型 + try { +// var fragment = parentFragmentManager.fragmentFactory.instantiate( +// itemModel.action.classLoader, +// itemModel.action.name +// ) as BaseFragment? + addActivityFragment(itemModel.action.getConstructor().newInstance() as BaseFragment) + } catch (e: Exception) { + Toast.makeText(context, "无法创建对象", Toast.LENGTH_SHORT).show() + e.printStackTrace() + } + } + } else if (itemModel.action is Action) { + itemModel.action.doAction(context) + } + } + + } + + } + +} \ No newline at end of file diff --git a/testapp/src/main/java/com/pic/testapp/WebViewFragment.java b/testapp/src/main/java/com/pic/testapp/WebViewFragment.java new file mode 100644 index 0000000..65eda90 --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/WebViewFragment.java @@ -0,0 +1,118 @@ +package com.pic.testapp; + +import android.graphics.Bitmap; +import android.net.http.SslError; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.SslErrorHandler; +import android.webkit.WebChromeClient; +import android.webkit.WebResourceRequest; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.pic.testapp.base.BindingFragment; +import com.pic.testapp.databinding.FragWebContainerBinding; +import com.tencent.smtt.sdk.URLUtil; + + +/** + * @author Lu + * @date 2024/10/26 19:31 + * @description + */ +public class WebViewFragment extends BindingFragment { + private WebView mWebView; + + @Override + protected FragWebContainerBinding onCreateBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) { + return FragWebContainerBinding.inflate(inflater, container, false); + } + + @Override + protected void initView() { + mWebView = new WebView(getContext()); + initWebView(); + mBinding.etWebUrl.setText(LocalStorage.getDefault().getString(LocalStorage.Key.WEB_VIEW_LAST_URL, "")); + mBinding.flWebContainer.addView(mWebView); + mBinding.tvGo.setOnClickListener(v -> openUrl(mBinding.etWebUrl.getText().toString())); + } + + private void initWebView() { + WebSettings setting = mWebView.getSettings(); + setting.setJavaScriptEnabled(true); + setting.setDomStorageEnabled(true); + setting.setDatabaseEnabled(true); + setting.setAllowUniversalAccessFromFileURLs(true); + + mWebView.setWebViewClient(new WebViewClient() { + @Override + public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) { + sslErrorHandler.proceed(); + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + mBinding.etWebUrl.setText(url); + mBinding.lpbProgress.setVisibility(View.VISIBLE); + recordLoadUrl(url); + } + + @Override + public void onPageFinished(WebView webView, String s) { + super.onPageFinished(webView, s); + mBinding.lpbProgress.setVisibility(View.INVISIBLE); + } + }); + + mWebView.setWebChromeClient(new WebChromeClient() { + @Override + public void onProgressChanged(WebView view, int newProgress) { + super.onProgressChanged(view, newProgress); + mBinding.lpbProgress.setProgress(newProgress); + } + }); + } + + private void recordLoadUrl(String url) { + if (TextUtils.isEmpty(url)) { + return; + } + if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url) || URLUtil.isFileUrl(url)) { + LocalStorage.getDefault().edit().putString(LocalStorage.Key.WEB_VIEW_LAST_URL, url).commit(); + } + } + + private void openUrl(String url) { + recordLoadUrl(url); + mWebView.loadUrl(url); + mBinding.etWebUrl.clearFocus(); + } + + @Override + protected void initData() { + + } + + @Override + public boolean onBackPressed() { + if (mWebView.canGoBack()) { + mWebView.goBack(); + return true; + } + return super.onBackPressed(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + mWebView.destroy(); + } +} diff --git a/testapp/src/main/java/com/pic/testapp/X5WebViewFragment.java b/testapp/src/main/java/com/pic/testapp/X5WebViewFragment.java new file mode 100644 index 0000000..db4a509 --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/X5WebViewFragment.java @@ -0,0 +1,136 @@ +package com.pic.testapp; + +import android.app.ProgressDialog; +import android.graphics.Bitmap; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.pic.testapp.base.BindingFragment; +import com.pic.testapp.databinding.FragWebContainerBinding; +import com.pic.testapp.vm.X5ViewModel; +import com.tencent.smtt.export.external.interfaces.SslError; +import com.tencent.smtt.export.external.interfaces.SslErrorHandler; +import com.tencent.smtt.sdk.URLUtil; +import com.tencent.smtt.sdk.WebChromeClient; +import com.tencent.smtt.sdk.WebSettings; +import com.tencent.smtt.sdk.WebView; +import com.tencent.smtt.sdk.WebViewClient; + +/** + * @author Lu + * @date 2024/10/26 16:06 + * @description + */ +public class X5WebViewFragment extends BindingFragment { + private X5ViewModel mViewModel; + private ProgressDialog progressDialog; + private WebView mWebView; + + @Override + protected FragWebContainerBinding onCreateBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) { + return FragWebContainerBinding.inflate(inflater, container, false); + } + + @Override + protected void initView() { + progressDialog = new ProgressDialog(getContext()); + progressDialog.show(); + mViewModel = getViewModel(X5ViewModel.class); + mViewModel.initX5().observe(this, aBoolean -> { + if (!aBoolean) { + Toast.makeText(getContext(), "x5内核未启用", Toast.LENGTH_SHORT).show(); + } + onViewReady(); + }); + } + + private void onViewReady() { + progressDialog.dismiss(); + mWebView = new WebView(getContext()); + initWebView(); + mBinding.etWebUrl.setText(LocalStorage.getDefault().getString(LocalStorage.Key.X5_WEB_VIEW_LAST_URL, "")); + mBinding.flWebContainer.addView(mWebView); + + mBinding.tvGo.setOnClickListener(v -> openUrl(mBinding.etWebUrl.getText().toString())); + } + + private void initWebView() { + WebSettings setting = mWebView.getSettings(); + setting.setJavaScriptEnabled(true); + setting.setDomStorageEnabled(true); + setting.setDatabaseEnabled(true); + setting.setAllowUniversalAccessFromFileURLs(true); + + mWebView.setWebViewClient(new WebViewClient() { + @Override + public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) { + sslErrorHandler.proceed(); + } + + + @Override + public void onPageStarted(WebView webView, String url, Bitmap bitmap) { + super.onPageStarted(webView, url, bitmap); + mBinding.etWebUrl.setText(url); + mBinding.lpbProgress.setVisibility(View.VISIBLE); + recordLoadUrl(url); + } + + @Override + public void onPageFinished(WebView webView, String s) { + super.onPageFinished(webView, s); + mBinding.lpbProgress.setVisibility(View.INVISIBLE); + } + }); + + mWebView.setWebChromeClient(new WebChromeClient() { + @Override + public void onProgressChanged(WebView webView, int i) { + super.onProgressChanged(webView, i); + mBinding.lpbProgress.setProgress(i); + } + }); + } + + private void openUrl(String url) { + recordLoadUrl(url); + mWebView.loadUrl(url); + mBinding.etWebUrl.clearFocus(); + } + + private void recordLoadUrl(String url) { + if (TextUtils.isEmpty(url)) { + return; + } + if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url) || URLUtil.isFileUrl(url)) { + LocalStorage.getDefault().edit().putString(LocalStorage.Key.X5_WEB_VIEW_LAST_URL, url).commit(); + } + } + + @Override + protected void initData() { + + } + + @Override + public boolean onBackPressed() { + if (mWebView.canGoBack()) { + mWebView.goBack(); + return true; + } + return super.onBackPressed(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + progressDialog.dismiss(); + mWebView.destroy(); + } +} diff --git a/testapp/src/main/java/com/pic/testapp/action/Action.java b/testapp/src/main/java/com/pic/testapp/action/Action.java new file mode 100644 index 0000000..0b51079 --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/action/Action.java @@ -0,0 +1,12 @@ +package com.pic.testapp.action; + +import android.content.Context; + +/** + * @author Lu + * @date 2024/10/26 19:45 + * @description + */ +public interface Action { + void doAction(Context context); +} diff --git a/testapp/src/main/java/com/pic/testapp/action/LoadBitmapAction.java b/testapp/src/main/java/com/pic/testapp/action/LoadBitmapAction.java new file mode 100644 index 0000000..2cce43d --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/action/LoadBitmapAction.java @@ -0,0 +1,32 @@ +package com.pic.testapp.action; + +import android.app.AlertDialog; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.widget.ImageView; + +import com.pic.testapp.R; + +/** + * @author Lu + * @date 2024/10/26 19:43 + * @description + */ +public class LoadBitmapAction implements Action { + + @Override + public void doAction(Context context) { + BitmapFactory.Options opt = new BitmapFactory.Options(); + opt.inPreferredConfig = Bitmap.Config.ARGB_8888; + + Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), android.R.mipmap.sym_def_app_icon, opt); + ImageView iv = new ImageView(context); + iv.setLayoutParams(new android.view.ViewGroup.LayoutParams(100, 100)); + iv.setImageBitmap(bitmap); + iv.setScaleType(ImageView.ScaleType.FIT_XY); + new AlertDialog.Builder(context) + .setView(iv) + .show(); + } +} diff --git a/testapp/src/main/java/com/pic/testapp/action/LoadHttpPicAction.java b/testapp/src/main/java/com/pic/testapp/action/LoadHttpPicAction.java new file mode 100644 index 0000000..61e3825 --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/action/LoadHttpPicAction.java @@ -0,0 +1,141 @@ +package com.pic.testapp.action; + +import android.app.AlertDialog; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.view.ViewGroup; +import android.view.Window; +import android.view.WindowManager; +import android.widget.ImageView; +import android.widget.Toast; + +import com.lu.magic.util.IOUtil; +import com.pic.testapp.util.AppExecutor; +import com.pic.testapp.util.LogUtil; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.ref.WeakReference; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okio.Buffer; +import okio.BufferedSource; + +/** + * @author Lu + * @date 2024/10/26 23:56 + * @description + */ +public class LoadHttpPicAction implements Action { + WeakReference mContextRef; + + @Override + public void doAction(Context context) { + mContextRef = new WeakReference<>(context); + LogUtil.d("doAction"); + AppExecutor.INSTANCE.runOnNetworkIo(() -> { + LogUtil.d("runOnNetworkIo"); + try { + doNetworkTask(); + } catch (Throwable e) { + LogUtil.d(e); + } + }); + } + + private InputStream getUrlStream(String picUrl) throws IOException { + InputStream iStream = null; + try { + URL url = new URL(picUrl); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setConnectTimeout(5000); + conn.setReadTimeout(5000); + iStream = conn.getInputStream(); + } catch (Exception e) { + LogUtil.d(e); + } + return iStream; + } + + private InputStream getOkHttpStream(String picUrl) throws IOException { + OkHttpClient.Builder builder = new OkHttpClient.Builder() + .callTimeout(5000L, TimeUnit.MILLISECONDS) + .connectTimeout(5000L, TimeUnit.MILLISECONDS) + .readTimeout(5000L, TimeUnit.MILLISECONDS) + .writeTimeout(5000L, TimeUnit.MILLISECONDS); + LogUtil.d("builder"); + OkHttpClient client = builder.build(); + LogUtil.d("client"); + Response response = client.newCall(new Request.Builder().url(picUrl).build()).execute(); + LogUtil.d("response"); + ResponseBody body = response.body(); + LogUtil.d("body"); + ResponseBody bodyNew = response.peekBody(Long.MAX_VALUE); +// byte[] bytes = IOUtil.readToBytes(bodyNew.byteStream()); + + //返回一个新的 +// BufferedSource peeked = bufferedSource.peek(); +// Buffer buffer = new Buffer(); +// peeked.request(Long.MAX_VALUE); +// buffer.write(peeked, Math.min(Long.MAX_VALUE, peeked.getBuffer().size())); +// byte[] bytes = buffer.readByteArray(); +// LogUtil.d("LoadHttpPicAction", "doNetworkTask", "bytes length", bytes.length); +// InputStream iStream = body.byteStream(); +// bytes = IOUtil.readToBytes(iStream); +// IOUtil.closeQuietly(peeked); + return body.byteStream(); + } + + public void doNetworkTask() throws IOException { +// String picUrl = "https://csdnimg.cn/release/blogv2/dist/pc/img/btnGuideSide1.gif"; + String picUrl = "https://ts2.cn.mm.bing.net/th?id=ORMS.96254be2fd646fe1f697a79490ffc4e9&pid=Wdp&w=612&h=328&qlt=90&c=1&rs=1&dpr=1.25&p=0"; +// String picUrl = "https://192.168.33.66/th?id=ORMS.96254be2fd646fe1f697a79490ffc4e9&pid=Wdp&w=612&h=328&qlt=90&c=1&rs=1&dpr=1.25&p=0"; + LogUtil.d(picUrl); + InputStream iStream = getUrlStream(picUrl); +// InputStream iStream = getOkHttpStream(picUrl); + LogUtil.d(iStream); + Bitmap bitmap = BitmapFactory.decodeStream(iStream); + LogUtil.d(bitmap); +// iStream.close(); + LogUtil.i("LoadHttpPicAction", "doNetworkTask"); + AppExecutor.INSTANCE.runOnUiThread(() -> { + doUiTask(bitmap); + }); + } + + private void doUiTask(Bitmap bitmap) { + if (bitmap == null) { + Toast.makeText(mContextRef.get(), "bitmap is null", Toast.LENGTH_SHORT).show(); + return; + } + LogUtil.i("LoadHttpPicAction", "doUiTask"); + Context context = mContextRef.get(); + if (context == null) { + return; + } + ImageView iv = new ImageView(context); + iv.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.MATCH_PARENT)); + iv.setScaleType(ImageView.ScaleType.FIT_CENTER); + iv.setImageBitmap(bitmap); + AlertDialog dialog = new AlertDialog.Builder(context) + .setView(iv) + .show(); + Window window = dialog.getWindow(); + WindowManager.LayoutParams lp = window.getAttributes(); + lp.width = bitmap.getWidth(); + lp.height = bitmap.getHeight(); + window.getDecorView().setPadding(0, 0, 0, 0); + } +} diff --git a/testapp/src/main/java/com/pic/testapp/base/BaseActivity.java b/testapp/src/main/java/com/pic/testapp/base/BaseActivity.java new file mode 100644 index 0000000..957eb9b --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/base/BaseActivity.java @@ -0,0 +1,76 @@ +package com.pic.testapp.base; + +import android.os.Bundle; + +import androidx.activity.OnBackPressedCallback; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.lifecycle.ViewModel; +import androidx.lifecycle.ViewModelProvider; + +import com.pic.testapp.R; + +/** + * @author Lu + * @date 2024/10/26 13:21 + * @description + */ +public class BaseActivity extends AppCompatActivity { + + private BaseFragment mRootFragment; + private ViewModelProvider mViewModelProvider; + + public VM getViewModel(Class vmClass) { + if (mViewModelProvider == null) { + mViewModelProvider = new ViewModelProvider(this); + } + return mViewModelProvider.get(vmClass); + } + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.act_frag_container_layout); + + getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { + @Override + public void handleOnBackPressed() { + BaseFragment fragment = getCurrentFragment(); + if (fragment != null && fragment.onBackPressed()) { + return; + } + if (fragment == null || isOnRootFragment()) { + finish(); + return; + } + popCurrentFragment(); + } + }); + + } + + private void popCurrentFragment() { + getSupportFragmentManager().popBackStack(); + } + + + public void addFragment(BaseFragment fragment) { + if (fragment == null) { + return; + } + if (mRootFragment == null) { + mRootFragment = fragment; + } + getSupportFragmentManager().beginTransaction().add(R.id.act_root_container, fragment).addToBackStack(fragment.getClass().getName()).commitAllowingStateLoss(); + } + + public boolean isOnRootFragment() { + return getSupportFragmentManager().findFragmentById(R.id.act_root_container) == mRootFragment; + } + + public BaseFragment getCurrentFragment() { + return (BaseFragment) getSupportFragmentManager().findFragmentById(R.id.act_root_container); + } + + +} diff --git a/testapp/src/main/java/com/pic/testapp/base/BaseFragment.java b/testapp/src/main/java/com/pic/testapp/base/BaseFragment.java new file mode 100644 index 0000000..04aa73a --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/base/BaseFragment.java @@ -0,0 +1,98 @@ +package com.pic.testapp.base; + +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; + +import androidx.annotation.LayoutRes; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; +import androidx.lifecycle.ViewModel; +import androidx.lifecycle.ViewModelProvider; + +/** + * @author Lu + * @date 2024/10/26 13:23 + * @description + */ +public abstract class BaseFragment extends Fragment { + private ViewModelProvider mViewModelProvider; + protected FrameLayout mRootView; + /** + * 处理返回事件 + * + * @return + */ + public boolean onBackPressed() { + return false; + } + + public VM getViewModel(Class vmClass) { + if (mViewModelProvider == null) { + mViewModelProvider = new ViewModelProvider(this); + } + return mViewModelProvider.get(vmClass); + } + + public BaseActivity getBaseActivity() { + return (BaseActivity) getActivity(); + } + + public void addActivityFragment(BaseFragment fragment) { + getBaseActivity().addFragment(fragment); + } + + + public boolean isOnRootFragment() { + return getBaseActivity().isOnRootFragment(); + } + + public BaseFragment getCurrentFragment() { + return getBaseActivity().getCurrentFragment(); + } + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + int resId = getLayoutResId(); + mRootView = new FrameLayout(getBaseActivity()); + mRootView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + mRootView.setClickable(true); + + //resId != Resources.ID_NULL + if (resId != 0 && resId != View.NO_ID) { + View.inflate(getContext(), resId, mRootView); + } + onRootViewCreate(mRootView); + return mRootView; + } + + protected void onRootViewCreate(FrameLayout rootView) { + mRootView.setBackgroundColor(getResources().getColor(android.R.color.background_light, getContext().getTheme())); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + initView(); + initData(); + } + + public T findViewById(int id) { + View view = getView(); + if (view == null) { + return null; + } + return view.findViewById(id); + } + + protected abstract @LayoutRes int getLayoutResId(); + + protected abstract void initView(); + + protected abstract void initData(); + +} diff --git a/testapp/src/main/java/com/pic/testapp/base/BindingFragment.java b/testapp/src/main/java/com/pic/testapp/base/BindingFragment.java new file mode 100644 index 0000000..3becb2d --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/base/BindingFragment.java @@ -0,0 +1,41 @@ +package com.pic.testapp.base; + +import android.content.res.Resources; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.viewbinding.ViewBinding; + +/** + * @author Lu + * @date 2024/10/26 15:12 + * @description + */ +public abstract class BindingFragment extends BaseFragment { + protected VB mBinding; + + @Override + protected int getLayoutResId() { + return View.NO_ID; + } + + @Override + protected void onRootViewCreate(FrameLayout rootView) { + super.onRootViewCreate(rootView); + mBinding = onCreateBinding(getLayoutInflater(), rootView); + mRootView.addView(mBinding.getRoot()); + } + + protected abstract VB onCreateBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container); + + @Override + protected abstract void initView(); + + @Override + protected abstract void initData(); +} diff --git a/testapp/src/main/java/com/pic/testapp/util/AppExecutor.kt b/testapp/src/main/java/com/pic/testapp/util/AppExecutor.kt new file mode 100644 index 0000000..162bcbd --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/util/AppExecutor.kt @@ -0,0 +1,43 @@ +package com.pic.testapp.util + +import android.os.Handler +import android.os.Looper +import java.util.concurrent.Executor +import java.util.concurrent.Executors + +object AppExecutor { + private val mDiskIO: Executor by lazy { DiskIOThreadExecutor() } + private val mNetworkIO: Executor by lazy { Executors.newFixedThreadPool(3) } + private val mMainThread: Executor by lazy { MainThreadExecutor() } + fun runOnDiskIo(command: Runnable) { + mDiskIO.execute(command) + } + + fun runOnNetworkIo(command: Runnable) { + mNetworkIO.execute(command) + } + + fun runOnUiThread(command: Runnable) { + mMainThread.execute(command) + } + + class MainThreadExecutor : Executor { + private val mainThreadHandler = Handler(Looper.getMainLooper()) + override fun execute(command: Runnable) { + if (Looper.myLooper() == Looper.getMainLooper()) { + command.run() + return + } + mainThreadHandler.post(command) + } + } + + class DiskIOThreadExecutor : Executor { + private val mDiskIO = Executors.newSingleThreadExecutor() + override fun execute(command: Runnable) { + mDiskIO.execute(command) + } + } + + +} diff --git a/testapp/src/main/java/com/pic/testapp/util/LogUtil.java b/testapp/src/main/java/com/pic/testapp/util/LogUtil.java new file mode 100644 index 0000000..d49621a --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/util/LogUtil.java @@ -0,0 +1,76 @@ +package com.pic.testapp.util; + +import android.util.Log; + +import java.lang.reflect.Array; +import java.util.Arrays; + +/** + * @author Lu + * @date 2024/10/26 22:25 + * @description + */ +public class LogUtil { + private static final String TAG = ">>>"; + + public static void d(Object... msg) { + printLog(Log.DEBUG, msg); + } + + + public static void e(Object... msg) { + printLog(Log.ERROR, msg); + } + + public static void w(Object... msg) { + printLog(Log.WARN, msg); + } + + public static void i(Object... msg) { + printLog(Log.INFO, msg); + } + + public static void v(Object... msg) { + printLog(Log.VERBOSE, msg); + } + + private static String buildMessage(Object... msg) { + StringBuilder msgBuilder = new StringBuilder(); + msgBuilder.append(Thread.currentThread().getName() + " "); + for (Object o : msg) { + if (o instanceof Throwable) { + msgBuilder.append(Log.getStackTraceString((Throwable) o)); + } else if (o == null) { + msgBuilder.append("null"); + } else if (o.getClass().isArray()) { + msgBuilder.append(Arrays.toString((Object[]) o)); + } else { + msgBuilder.append(o); + } + msgBuilder.append(" "); + } + return msgBuilder.toString(); + } + + + private static void printLog(int level, Object[] msg) { + switch (level) { + case Log.VERBOSE: + Log.v(TAG, buildMessage(msg)); + break; + case Log.INFO: + Log.i(TAG, buildMessage(msg)); + break; + case Log.WARN: + Log.w(TAG, buildMessage(msg)); + break; + case Log.ERROR: + Log.e(TAG, buildMessage(msg)); + break; + case Log.DEBUG: + default: + Log.d(TAG, buildMessage(msg)); + break; + } + } +} diff --git a/testapp/src/main/java/com/pic/testapp/vm/X5ViewModel.java b/testapp/src/main/java/com/pic/testapp/vm/X5ViewModel.java new file mode 100644 index 0000000..04c55b7 --- /dev/null +++ b/testapp/src/main/java/com/pic/testapp/vm/X5ViewModel.java @@ -0,0 +1,62 @@ +package com.pic.testapp.vm; + +import android.content.Context; + +import androidx.constraintlayout.widget.ConstraintLayout; +import androidx.lifecycle.MutableLiveData; +import androidx.lifecycle.ViewModel; + +import com.pic.testapp.App; +import com.pic.testapp.util.LogUtil; +import com.tencent.smtt.export.external.TbsCoreSettings; +import com.tencent.smtt.sdk.QbSdk; +import com.tencent.smtt.utils.LogFileUtils; + +import java.util.HashMap; +import java.util.logging.LogManager; + +/** + * @author Lu + * @date 2024/10/26 20:08 + * @description + */ +public class X5ViewModel extends ViewModel { + private MutableLiveData mX5InitLiveData; + + public MutableLiveData initX5() { + if (mX5InitLiveData == null) { + mX5InitLiveData = new MutableLiveData<>(); + } + if (QbSdk.isTbsCoreInited()) { + mX5InitLiveData.postValue(QbSdk.isX5Core()); + LogUtil.d("isTbsCoreInited true"); + return mX5InitLiveData; + } + + // 在调用TBS初始化、创建WebView之前进行如下配置 + HashMap map = new HashMap(); + map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true); + map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true); + QbSdk.initTbsSettings(map); + QbSdk.initX5Environment(App.getInstance(), new QbSdk.PreInitCallback() { + @Override + public void onCoreInitFinished() { + // 内核初始化完成,可能为系统内核,也可能为系统内核 + LogUtil.d("onCoreInitFinished"); + } + + /** + * 预初始化结束 + * 由于X5内核体积较大,需要依赖网络动态下发,所以当内核不存在的时候,默认会回调false,此时将会使用系统内核代替 + * @param isX5 是否使用X5内核 + */ + @Override + public void onViewInitFinished(boolean isX5) { + LogUtil.d("onViewInitFinished isX5:" + isX5); + mX5InitLiveData.postValue(QbSdk.isX5Core()); + + } + }); + return mX5InitLiveData; + } +} diff --git a/testapp/src/main/res/drawable-v24/ic_launcher_foreground.xml b/testapp/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/testapp/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/testapp/src/main/res/drawable/ic_launcher_background.xml b/testapp/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07d5da9 --- /dev/null +++ b/testapp/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/testapp/src/main/res/layout/act_frag_container_layout.xml b/testapp/src/main/res/layout/act_frag_container_layout.xml new file mode 100644 index 0000000..ceb2ff6 --- /dev/null +++ b/testapp/src/main/res/layout/act_frag_container_layout.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/testapp/src/main/res/layout/frag_main_layout.xml b/testapp/src/main/res/layout/frag_main_layout.xml new file mode 100644 index 0000000..9f4c6ef --- /dev/null +++ b/testapp/src/main/res/layout/frag_main_layout.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/testapp/src/main/res/layout/frag_web_container.xml b/testapp/src/main/res/layout/frag_web_container.xml new file mode 100644 index 0000000..9f41a24 --- /dev/null +++ b/testapp/src/main/res/layout/frag_web_container.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testapp/src/main/res/layout/item_text_inline_block.xml b/testapp/src/main/res/layout/item_text_inline_block.xml new file mode 100644 index 0000000..e7cbb86 --- /dev/null +++ b/testapp/src/main/res/layout/item_text_inline_block.xml @@ -0,0 +1,30 @@ + + + + + \ No newline at end of file diff --git a/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/testapp/src/main/res/mipmap-hdpi/ic_launcher.webp b/testapp/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/testapp/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/testapp/src/main/res/mipmap-mdpi/ic_launcher.webp b/testapp/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/testapp/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/testapp/src/main/res/mipmap-xhdpi/ic_launcher.webp b/testapp/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/testapp/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/testapp/src/main/res/values-night/themes.xml b/testapp/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..b7e6280 --- /dev/null +++ b/testapp/src/main/res/values-night/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/testapp/src/main/res/values/colors.xml b/testapp/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/testapp/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/testapp/src/main/res/values/strings.xml b/testapp/src/main/res/values/strings.xml new file mode 100644 index 0000000..ae0adfd --- /dev/null +++ b/testapp/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + testapp + \ No newline at end of file diff --git a/testapp/src/main/res/values/themes.xml b/testapp/src/main/res/values/themes.xml new file mode 100644 index 0000000..71b3fc6 --- /dev/null +++ b/testapp/src/main/res/values/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/testapp/src/test/java/com/pic/testapp/ExampleUnitTest.kt b/testapp/src/test/java/com/pic/testapp/ExampleUnitTest.kt new file mode 100644 index 0000000..f21a5b7 --- /dev/null +++ b/testapp/src/test/java/com/pic/testapp/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.pic.testapp + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file