feat: 添加 WebView 无缓存配置和运行时缓存清理逻辑,优化页面加载体验

This commit is contained in:
Booker
2026-05-26 18:38:36 +07:00
parent 81f0f342a9
commit ca25c2d706
3 changed files with 270 additions and 19 deletions

View File

@@ -11,18 +11,22 @@ import android.net.Uri
import android.os.Build
import android.util.Base64
import android.util.Log
import android.webkit.ServiceWorkerController
import android.webkit.WebSettings
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import org.conscrypt.Conscrypt
import java.security.Security
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.webviewflutter.WebViewFlutterAndroidExternalApi
import java.io.ByteArrayOutputStream
import java.io.File
class MainActivity : FlutterActivity() {
private val CHANNEL = "io.openim.flutter.openim/apk_info"
private val SHELL_BRANDING_CHANNEL = "io.openim.flutter.im_webview_app/shell_branding"
private val WEBVIEW_CACHE_CHANNEL = "io.openim.flutter.im_webview_app/webview_cache"
private val TAG = "MainActivity"
private val MAX_BRANDING_ICON_SIZE = 192
@@ -107,6 +111,55 @@ class MainActivity : FlutterActivity() {
}
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, WEBVIEW_CACHE_CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"configureNoCache" -> {
val webViewId = readLongArgument(call.argument<Any>("webViewId"))
if (webViewId == null) {
result.error("INVALID_ARGUMENT", "webViewId 不能为空", null)
return@setMethodCallHandler
}
try {
result.success(configureWebViewNoCache(flutterEngine, webViewId))
} catch (e: Exception) {
result.error("ERROR", "无法配置 WebView 缓存策略: ${e.message}", null)
}
}
else -> {
result.notImplemented()
}
}
}
}
private fun readLongArgument(value: Any?): Long? {
return when (value) {
is Int -> value.toLong()
is Long -> value
is Number -> value.toLong()
else -> null
}
}
private fun configureWebViewNoCache(flutterEngine: FlutterEngine, webViewId: Long): Boolean {
val webView = WebViewFlutterAndroidExternalApi.getWebView(flutterEngine, webViewId) ?: return false
webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
webView.clearCache(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
ServiceWorkerController
.getInstance()
.serviceWorkerWebSettings
.cacheMode = WebSettings.LOAD_NO_CACHE
} catch (e: Exception) {
Log.w(TAG, "ServiceWorker cache mode configure failed: ${e.message}")
}
}
return true
}
private fun getCurrentAppName(): String {