电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Android 解決WebView多進程崩潰的方法

瀏覽:44日期:2022-09-20 13:33:38
問題

在android 9.0系統上如果多個進程使用WebView需要使用官方提供的api在子進程中給webview的數據文件夾設置后綴:

WebView.setDataDirectorySuffix(suffix);

否則將會報出以下錯誤:

Using WebView from more than one process at once with the same data directory is not supported. https://crbug.com/5583771 com.android.webview.chromium.WebViewChromiumAwInit.startChromiumLocked(WebViewChromiumAwInit.java:63)2 com.android.webview.chromium.WebViewChromiumAwInitForP.startChromiumLocked(WebViewChromiumAwInitForP.java:3)3 com.android.webview.chromium.WebViewChromiumAwInit$3.run(WebViewChromiumAwInit.java:3)4 android.os.Handler.handleCallback(Handler.java:873)5 android.os.Handler.dispatchMessage(Handler.java:99)6 android.os.Looper.loop(Looper.java:220)7 android.app.ActivityThread.main(ActivityThread.java:7437)8 java.lang.reflect.Method.invoke(Native Method)9 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:500)10 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:865)

通過使用官方提供的方法后問題只減少了一部分,從bugly后臺依然能收到此問題的大量崩潰信息,以至于都沖上了崩潰問題Top3。

問題分析

從源碼分析調用鏈最終調用到了AwDataDirLock類中的lock方法。

public class WebViewChromiumAwInit { protected void startChromiumLocked() { ... AwBrowserProcess.start(); ... }}public final class AwBrowserProcess { public static void start() { ... AwDataDirLock.lock(appContext);}

AwDataDirLock.java

abstract class AwDataDirLock { private static final String TAG = 'AwDataDirLock'; private static final String EXCLUSIVE_LOCK_FILE = 'webview_data.lock'; // This results in a maximum wait time of 1.5s private static final int LOCK_RETRIES = 16; private static final int LOCK_SLEEP_MS = 100; private static RandomAccessFile sLockFile; private static FileLock sExclusiveFileLock; static void lock(final Context appContext) { try (ScopedSysTraceEvent e1 = ScopedSysTraceEvent.scoped('AwDataDirLock.lock'); StrictModeContext ignored = StrictModeContext.allowDiskWrites()) { if (sExclusiveFileLock != null) { // We have already called lock() and successfully acquired the lock in this process. // This shouldn’t happen, but is likely to be the result of an app catching an // exception thrown during initialization and discarding it, causing us to later // attempt to initialize WebView again. There’s no real advantage to failing the // locking code when this happens; we may as well count this as the lock being // acquired and let init continue (though the app may experience other problems // later). return; } // If we already called lock() but didn’t succeed in getting the lock, it’s possible the // app caught the exception and tried again later. As above, there’s no real advantage // to failing here, so only open the lock file if we didn’t already open it before. if (sLockFile == null) { String dataPath = PathUtils.getDataDirectory(); File lockFile = new File(dataPath, EXCLUSIVE_LOCK_FILE); try { // Note that the file is kept open intentionally. sLockFile = new RandomAccessFile(lockFile, 'rw'); } catch (IOException e) { // Failing to create the lock file is always fatal; even if multiple processes // are using the same data directory we should always be able to access the file // itself. throw new RuntimeException('Failed to create lock file ' + lockFile, e); } } // Android versions before 11 have edge cases where a new instance of an app process can // be started while an existing one is still in the process of being killed. This can // still happen on Android 11+ because the platform has a timeout for waiting, but it’s // much less likely. Retry the lock a few times to give the old process time to fully go // away. for (int attempts = 1; attempts <= LOCK_RETRIES; ++attempts) { try { sExclusiveFileLock = sLockFile.getChannel().tryLock(); } catch (IOException e) { // Older versions of Android incorrectly throw IOException when the flock() // call fails with EAGAIN, instead of returning null. Just ignore it. } if (sExclusiveFileLock != null) { // We got the lock; write out info for debugging. writeCurrentProcessInfo(sLockFile); return; } // If we’re not out of retries, sleep and try again. if (attempts == LOCK_RETRIES) break; try { Thread.sleep(LOCK_SLEEP_MS); } catch (InterruptedException e) { } } // We failed to get the lock even after retrying. // Many existing apps rely on this even though it’s known to be unsafe. // Make it fatal when on P for apps that target P or higher String error = getLockFailureReason(sLockFile); boolean dieOnFailure = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && appContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.P; if (dieOnFailure) { throw new RuntimeException(error); } else { Log.w(TAG, error); } } } private static void writeCurrentProcessInfo(final RandomAccessFile file) { try { // Truncate the file first to get rid of old data. file.setLength(0); file.writeInt(Process.myPid()); file.writeUTF(ContextUtils.getProcessName()); } catch (IOException e) { // Don’t crash just because something failed here, as it’s only for debugging. Log.w(TAG, 'Failed to write info to lock file', e); } } private static String getLockFailureReason(final RandomAccessFile file) { final StringBuilder error = new StringBuilder('Using WebView from more than one process at ' + 'once with the same data directory is not supported. https://crbug.com/558377 ' + ': Current process '); error.append(ContextUtils.getProcessName()); error.append(' (pid ').append(Process.myPid()).append('), lock owner '); try { int pid = file.readInt(); String processName = file.readUTF(); error.append(processName).append(' (pid ').append(pid).append(')'); // Check the status of the pid holding the lock by sending it a null signal. // This doesn’t actually send a signal, just runs the kernel access checks. try { Os.kill(pid, 0); // No exception means the process exists and has the same uid as us, so is // probably an instance of the same app. Leave the message alone. } catch (ErrnoException e) { if (e.errno == OsConstants.ESRCH) { // pid did not exist - the lock should have been released by the kernel, // so this process info is probably wrong. error.append(' doesn’t exist!'); } else if (e.errno == OsConstants.EPERM) { // pid existed but didn’t have the same uid as us. // Most likely the pid has just been recycled for a new process error.append(' pid has been reused!'); } else { // EINVAL is the only other documented return value for kill(2) and should never // happen for signal 0, so just complain generally. error.append(' status unknown!'); } } } catch (IOException e) { // We’ll get IOException if we failed to read the pid and process name; e.g. if the // lockfile is from an old version of WebView or an IO error occurred somewhere. error.append(' unknown'); } return error.toString(); }}

lock方法會對webview數據目錄中的webview_data.lock文件在for循環中嘗試加鎖16次,注釋中也說明了這么做的原因:可能出現的極端情況是一個舊進程正在被殺死時一個新的進程啟動了,看來Google工程師對這個問題也很頭痛;如果加鎖成功會將該進程id和進程名寫入到文件,如果加鎖失敗則會拋出異常。所以在android9.0以上檢測應用是否存在多進程共用WebView數據目錄的原理就是進程持有WebView數據目錄中的webview_data.lock文件的鎖。所以如果子進程也對相同文件嘗試加鎖則會導致應用崩潰。

解決方案

目前大部分手機會在應用崩潰時自動重啟應用,猜測當手機系統運行較慢時這時就會出現注釋中提到的當一個舊進程正在被殺死時一個新的進程啟動了的情況。既然獲取文件鎖失敗就會發生崩潰,并且該文件只是用于加鎖判斷是否存在多進程共用WebView數據目錄,每次加鎖成功都會重新寫入對應進程信息,那么我們可以在應用啟動時對該文件嘗試加鎖,如果加鎖失敗就刪除該文件并重新創建,加鎖成功就立即釋放鎖,這樣當系統嘗試加鎖時理論上是可以加鎖成功的,也就避免了這個問題的發生。

private static void handleWebviewDir(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { return; } try { String suffix = ''; String processName = getProcessName(context); if (!TextUtils.equals(context.getPackageName(), processName)) {//判斷不等于默認進程名稱 suffix = TextUtils.isEmpty(processName) ? context.getPackageName() : processName; WebView.setDataDirectorySuffix(suffix); suffix = '_' + suffix; } tryLockOrRecreateFile(context,suffix); } catch (Exception e) { e.printStackTrace(); } } @TargetApi(Build.VERSION_CODES.P) private static void tryLockOrRecreateFile(Context context,String suffix) { String sb = context.getDataDir().getAbsolutePath() + '/app_webview'+suffix+'/webview_data.lock'; File file = new File(sb); if (file.exists()) { try { FileLock tryLock = new RandomAccessFile(file, 'rw').getChannel().tryLock(); if (tryLock != null) { tryLock.close(); } else { createFile(file, file.delete()); } } catch (Exception e) { e.printStackTrace(); boolean deleted = false; if (file.exists()) { deleted = file.delete(); } createFile(file, deleted); } } } private static void createFile(File file, boolean deleted){ try { if (deleted && !file.exists()) { file.createNewFile(); } } catch (Exception e) { e.printStackTrace(); } }

使用此方案應用上線后該問題崩潰次數減少了90%以上。也許Google工程師應該考慮下換一種技術方案檢測應用是否存在多進程共用WebView數據目錄。

以上就是Android 解決WebView多進程崩潰的方法的詳細內容,更多關于Android 解決WebView多進程崩潰的資料請關注好吧啦網其它相關文章!

標簽: Android
相關文章:
主站蜘蛛池模板: 新密高铝耐火砖,轻质保温砖价格,浇注料厂家直销-郑州荣盛窑炉耐火材料有限公司 | RS系列电阻器,RK_RJ启动调整电阻器,RQ_RZ电阻器-上海永上电器有限公司 | 数码管_LED贴片灯_LED数码管厂家-无锡市冠卓电子科技有限公司 | 临海涌泉蜜桔官网|涌泉蜜桔微商批发代理|涌泉蜜桔供应链|涌泉蜜桔一件代发 | ★店家乐|服装销售管理软件|服装店收银系统|内衣店鞋店进销存软件|连锁店管理软件|收银软件手机版|会员管理系统-手机版,云版,App | 2025黄道吉日查询、吉时查询、老黄历查询平台- 黄道吉日查询网 | 上海logo设计| 立式矫直机_卧式矫直机-无锡金矫机械制造有限公司 | 丝杆升降机-不锈钢丝杆升降机-非标定制丝杆升降机厂家-山东鑫光减速机有限公司 | 伶俐嫂培训学校_月嫂培训班在哪里报名学费是多少_月嫂免费政府培训中心推荐 | 南京展台搭建-南京展会设计-南京展览设计公司-南京展厅展示设计-南京汇雅展览工程有限公司 | 次氯酸钠厂家,涉水级次氯酸钠,三氯化铁生产厂家-淄博吉灿化工 | 讲师宝经纪-专业培训机构师资供应商_培训机构找讲师、培训师、讲师经纪就上讲师宝经纪 | 天然鹅卵石滤料厂家-锰砂滤料-石英砂滤料-巩义东枫净水 | 祝融环境-地源热泵多恒系统高新技术企业,舒适生活环境缔造者! | 甲级防雷检测仪-乙级防雷检测仪厂家-上海胜绪电气有限公司 | 洛阳永磁工业大吊扇研发生产-工厂通风降温解决方案提供商-中实洛阳环境科技有限公司 | 论文查重_免费论文查重_知网学术不端论文查重检测系统入口_论文查重软件 | 桨叶搅拌机_螺旋挤压/方盒旋切造粒机厂家-无锡市鸿诚输送机械有限公司 | 科研ELISA试剂盒,酶联免疫检测试剂盒,昆虫_植物ELISA酶免试剂盒-上海仁捷生物科技有限公司 | 东亚液氮罐-液氮生物容器-乐山市东亚机电工贸有限公司 | 亿立分板机_曲线_锯片式_走刀_在线式全自动_铣刀_在线V槽分板机-杭州亿协智能装备有限公司 | 智能监控-安防监控-监控系统安装-弱电工程公司_成都万全电子 | 烟台螺纹,烟台H型钢,烟台钢材,烟台角钢-烟台市正丰金属材料有限公司 | BAUER减速机|ROSSI-MERSEN熔断器-APTECH调压阀-上海爱泽工业设备有限公司 | 全自动包衣机-无菌分装隔离器-浙江迦南科技股份有限公司 | 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 臭氧老化试验箱,高低温试验箱,恒温恒湿试验箱,防水试验设备-苏州亚诺天下仪器有限公司 | 浙江富广阀门有限公司| 青岛侦探_青岛侦探事务所_青岛劝退小三_青岛调查出轨取证公司_青岛婚外情取证-青岛探真调查事务所 | 济南品牌包装设计公司_济南VI标志设计公司_山东锐尚文化传播 | 热工多功能信号校验仪-热电阻热电偶校验仿真仪-金湖虹润仪表 | 广东恩亿梯电源有限公司【官网】_UPS不间断电源|EPS应急电源|模块化机房|电动汽车充电桩_UPS电源厂家(恩亿梯UPS电源,UPS不间断电源,不间断电源UPS) | 选矿设备,选矿生产线,选矿工艺,选矿技术-昆明昆重矿山机械 | 泰国试管婴儿_泰国第三代试管婴儿_泰国试管婴儿费用/多少钱_孕泰来 | 上海办公室装修公司_办公室设计_直营办公装修-羚志悦装 | 河南不锈钢水箱_地埋水箱_镀锌板水箱_消防水箱厂家-河南联固供水设备有限公司 | 紫外线老化试验箱_uv紫外线老化试验箱价格|型号|厂家-正航仪器设备 | 新能源汽车教学设备厂家报价[汽车教学设备运营18年]-恒信教具 | 润滑脂-高温润滑脂-轴承润滑脂-食品级润滑油-索科润滑油脂厂家 | 美能达分光测色仪_爱色丽分光测色仪-苏州方特电子科技有限公司 |