Using WebView from more than one process at once with the same data directory is not supported.

有效解决WebView多进程崩溃(续) - 掘金 (juejin.cn)

private fun handleWebViewDir(context: Context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
        return
    }
    try {
        val pathSet: MutableSet<String> = HashSet()
        var suffix = ""
        val dataPath = context.dataDir.absolutePath
        val webViewDir = "/app_webview"
        val huaweiWebViewDir = "/app_hws_webview"
        val lockFile = "/webview_data.lock"
        val processName = getProcessName()
        if (!TextUtils.equals(context.packageName, processName)) { //判断不等于默认进程名称
            suffix = if (TextUtils.isEmpty(processName)) context.packageName else processName
            WebView.setDataDirectorySuffix(suffix)
            suffix = "_$suffix"
            pathSet.add(dataPath + webViewDir + suffix + lockFile)
            if (checkIsHuaweiRom()) {
                pathSet.add(dataPath + huaweiWebViewDir + suffix + lockFile)
            }
        } else {
            //主进程
            suffix = "_$processName"
            pathSet.add(dataPath + webViewDir + lockFile) //默认未添加进程名后缀
            pathSet.add(dataPath + webViewDir + suffix + lockFile) //系统自动添加了进程名后缀
            if (checkIsHuaweiRom()) { //部分华为手机更改了webview目录名
                pathSet.add(dataPath + huaweiWebViewDir + lockFile)
                pathSet.add(dataPath + huaweiWebViewDir + suffix + lockFile)
            }
        }
        for (path in pathSet) {
            val file = File(path)
            if (file.exists()) {
                tryLockOrRecreateFile(file)
                break
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

@TargetApi(Build.VERSION_CODES.P)
private fun tryLockOrRecreateFile(file: File) {
    try {
        val tryLock: FileLock? = RandomAccessFile(file, "rw").channel.tryLock()
        if (tryLock != null) {
            tryLock.close()
        } else {
            createFile(file, file.delete())
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        var deleted = false
        if (file.exists()) {
            deleted = file.delete()
        }
        createFile(file, deleted)
    }
}

private fun createFile(file: File, deleted: Boolean) {
    try {
        if (deleted && !file.exists()) {
            file.createNewFile()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值