国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Using WebView from more than one process

這篇具有很好參考價(jià)值的文章主要介紹了Using WebView from more than one process。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

關(guān)于作者:CSDN內(nèi)容合伙人、技術(shù)專家, 從零開始做日活千萬級APP。
專注于分享各領(lǐng)域原創(chuàng)系列文章 ,擅長java后端、移動開發(fā)、商業(yè)變現(xiàn)、人工智能等,希望大家多多支持。
未經(jīng)允許不得轉(zhuǎn)載

Using WebView from more than one process,問題記錄,webview

一、導(dǎo)讀

我們繼續(xù)總結(jié)學(xué)習(xí)遇到的問題,溫故知新。

今天遇到一個線上問題,啟動就閃退,比較坑,在此做一個記錄,防止掉坑。

本文記錄一次bug解決的過程,

Using WebView from more than one process

二、概覽

今天將 targetSdkVersion 的版升級到了29,出現(xiàn)了一些奇怪的報(bào)錯,日志如下

Fatal Exception: java.lang.RuntimeException: Using WebView from more than one process at once with the same data directory is not supported. 
https://crbug.com/558377 : Current process com.xx.xxapp(pid 13862), lock owner com.xx.xx.xxAPP (pid 13559)
       at org.chromium.android_webview.AwDataDirLock.b(AwDataDirLock.java:27)
       at as0.i(as0.java:30)
       at Zr0.run(Zr0.java:2)
       at android.os.Handler.handleCallback(Handler.java:883)
       at android.os.Handler.dispatchMessage(Handler.java:100)
       at android.os.Looper.loop(Looper.java:224)
       at android.app.ActivityThread.main(ActivityThread.java:7520)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

三、問題過程

我們查看文檔發(fā)現(xiàn), google 文檔
在android 9.0系統(tǒng)上如果多個進(jìn)程使用WebView需要使用官方提供的api在子進(jìn)程中給webview的數(shù)據(jù)文件夾設(shè)置后綴:

如果不設(shè)置,則會報(bào)錯,不過這個影響范圍有限,影響范圍: Android 9及以上 且targetSdkVersion >= 28

    Starting Android Pie (API 28), Google isn't allowing using a single WebView instance in 2 different processes.
    
    WebView.setDataDirectorySuffix(suffix);

官方提供方案

protected void attachBaseContext(Context base) {
    mApplicationContext = base;
    webViewSetPath(this);
  }  


public void webViewSetPath(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        String processName = SpecialUtils.getCurProcessName(context);
        
        // 根據(jù)進(jìn)程名稱,設(shè)置多個目錄
        if(!CommonConstant.NEW_PACKAGE_NAME.equals(processName)){
            WebView.setDataDirectorySuffix(getString(processName,"這里隱藏名字,自己設(shè)置個目錄"));
        }
    }
}

public String getString(String processName, String defValue) {
    return TextUtils.isEmpty(processName) ? defValue : processName;
}

通過使用官方提供的方法后,實(shí)際在項(xiàng)目中運(yùn)用 application中設(shè)置多個存儲目錄,雖然能減少問題發(fā)生的次數(shù),但從bugly后臺依然能收到此問題的大量崩潰信

源碼追蹤

那么這個問題發(fā)生的原因究竟是什么?一起來分析下拋出這個異常的邏輯吧
https://chromium.googlesource.com/chromium/src/+/refs/heads/main/android_webview/java/src/org/chromium/android_webview/AwDataDirLock.java#126

從源碼分析調(diào)用鏈最終調(diào)用到了AwDataDirLock類中的lock方法

abstract class AwDataDirLock {

    static void lock(final Context appContext) {
        try (ScopedSysTraceEvent e1 = ScopedSysTraceEvent.scoped("AwDataDirLock.lock");
             StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
            if (sExclusiveFileLock != null) {
                我們已經(jīng)調(diào)用了lock(),并在此過程中成功獲取了鎖
                return;
            }
            
            如果我們已經(jīng)調(diào)用了lock(),但沒有成功獲得鎖,則可能應(yīng)用程序捕獲到異常,進(jìn)行自動重啟。
            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) {
                    throw new RuntimeException("Failed to create lock file " + lockFile, e);
                }
            }
            
            對webview數(shù)據(jù)目錄中的webview_data.lock文件在for循環(huán)中嘗試加鎖16for (int attempts = 1; attempts <= LOCK_RETRIES; ++attempts) {
                try {
                    sExclusiveFileLock = sLockFile.getChannel().tryLock();
                } catch (IOException e) {
                }
                
                如果加鎖成功會將該進(jìn)程id和進(jìn)程名寫入到文件
                if (sExclusiveFileLock != null) {
                    writeCurrentProcessInfo(sLockFile);
                    return;
                }
                if (attempts == LOCK_RETRIES) break;
                try {
                    Thread.sleep(LOCK_SLEEP_MS);
                } catch (InterruptedException e) {
                }
            }
            
            如果加鎖失敗則會拋出異常
            // Using WebView from more than one process 
            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 {
            }
        }
    }
}

分析了原因,我們來看看解決思路,我們可以在應(yīng)用啟動時(shí)對該文件嘗試加鎖,如果加鎖失敗就刪除該文件并重新創(chuàng)建,加鎖成功就立即釋放鎖,這樣當(dāng)系統(tǒng)嘗試加鎖時(shí)理論上是可以加鎖成功的。
通過檢查目標(biāo)目錄的文件鎖,如果能夠獲得到鎖,就表明無異常;如果獲取不到文件鎖,再次重新設(shè)置存儲目錄。


public class WebViewUtil {

    public static void handleWebViewDir(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            return;
        }
        try {
            String suffix = "";
            String processName = getCurProcessName(context);
            if (!TextUtils.equals(context.getPackageName(), processName)) {//判斷不等于默認(rèn)進(jìn)程名稱
                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();
        }
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess == null) {
                continue;
            }
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

}

但是這樣上線后發(fā)現(xiàn)還有問題,原因是不同機(jī)型,目錄可能不一樣,
我們自己使用debug包查看webview數(shù)據(jù)目錄發(fā)現(xiàn)系統(tǒng)默認(rèn)添加了進(jìn)程名后綴,這是由于用戶更新了手機(jī)系統(tǒng)導(dǎo)致,
使用華為mate20X測試調(diào)用 WebView.selDataDirecloySufx 自定義后綴已不生效,會默認(rèn)強(qiáng)制指定后綴為進(jìn)程名,
另外還發(fā)現(xiàn)部分華為手機(jī)直接將webview目錄名app webview改為了app hws webview。

Using WebView from more than one process,問題記錄,webview
綜上所述,我們需要針對不同手機(jī)系統(tǒng)遍歷可能的文件路徑,最新解決代碼如下:

```java

    public static void handleWebViewDir(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            return;
        }

        String webViewDir = "/app_webview";
        String huaweiWebViewDir = "/app_hws_webview";
        String lockFile = "/webview_data.lock";
        
        try {
            xxx
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @TargetApi(Build.VERSION_CODES.P)
    private static void tryLockOrRecreateFile(String path) {
        File file = new File(path);
        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) {
                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()) {
                boolean var2 = file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

然后在application的oncreate方法中調(diào)用 handleWebViewDir();

參考文章:
文章 1
文章 2
文章 3

四、 推薦閱讀

Java 專欄

SQL 專欄

數(shù)據(jù)結(jié)構(gòu)與算法

Android學(xué)習(xí)專欄

未經(jīng)允許不得轉(zhuǎn)載

Using WebView from more than one process,問題記錄,webview文章來源地址http://www.zghlxwxcb.cn/news/detail-838401.html

到了這里,關(guān)于Using WebView from more than one process的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【解決】RuntimeError: Boolean value of Tensor with more than one value is ambiguous

    在用pytorch進(jìn)行損失函數(shù)計(jì)算時(shí),報(bào)錯誤: 翻譯過來就是說: 具有多個值的張量的布爾值不明確? 我是這報(bào)錯: 啥意思?,你問我,我也不知道呀!、、、 ?錯誤原因分析: 其實(shí)是,因?yàn)槲覔p失函數(shù)調(diào)用時(shí)沒有初始化,所以導(dǎo)致報(bào)錯 其實(shí)我是初始化了,但是因?yàn)闆]有+(),

    2024年02月16日
    瀏覽(19)
  • keil5版本時(shí)“error: L6235E: More than one section matches selector - cannot all be FIRST/LAST.”

    keil5版本時(shí)“error: L6235E: More than one section matches selector - cannot all be FIRST/LAST.”

    前言:在使用keil 5版本時(shí),創(chuàng)建工程后稍不留神會出現(xiàn)問題“.Objectsproject.sct(7): error: L6235E: More than one section matches selector - cannot all be FIRST/LAST.”???? 保姆教程??! 問題描述: 出現(xiàn)下類問題,無疑是指你的啟動文件不止一個,例如“startup_stm32f10x_md.s”,就是創(chuàng)建工程時(shí),

    2024年02月16日
    瀏覽(20)
  • ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.al

    這個錯誤通常發(fā)生在你在使用numpy數(shù)組作為if語句的條件時(shí)。在這種情況下,Python會嘗試使用該數(shù)組中的所有元素來確定if語句的真假。由于numpy數(shù)組可能包含多個元素,因此Python會拋出ValueError錯誤,因?yàn)樗恢廊绾翁幚矶鄠€元素的數(shù)組。 解決方法就是使用 a.all() or a.any() 替

    2024年02月16日
    瀏覽(25)
  • 中國工科研究生200多篇英文論文中最常見的習(xí)慣(The Most Common Habits from more than 200 English Papers written by Gradua)

    中國工科研究生200多篇英文論文中最常見的習(xí)慣(The Most Common Habits from more than 200 English Papers written by Gradua)

    原文地址:http://staff.ustc.edu.cn/~jpq/writing/The%20Most%20Common%20Habits.pdf 本文介紹了中國作家在200多篇英語科技論文中觀察到的一些最常見的漢英習(xí)慣。這些習(xí)慣會被解釋,在大多數(shù)情況下,來自實(shí)際論文的示例文本會與首選文本一起給出。試圖解釋如何糾正和防止此類錯誤。在某

    2024年02月08日
    瀏覽(21)
  • 徹底解決ES 數(shù)據(jù)查詢 from + size must be less than or equal to:xxx 問題

    ES分頁查詢時(shí)出現(xiàn)超過一萬頁就爆出這個錯誤:Result window is too large, from + size must be less than or equal to: [10000] but… 該錯誤是由于es默認(rèn)設(shè)置最大頁數(shù)為一萬的原因?qū)е碌模@樣設(shè)置也是為了防止OOM。 第一種解決方式: 防止這個錯誤出現(xiàn)是設(shè)置 index.max_result_window的值。但是這種

    2024年02月14日
    瀏覽(24)
  • Centos 報(bào)錯 Repository extras is listed more than once in the configuration

    使用 yum update -y 報(bào)錯 Repository extras is listed more than once in the configuration 2020 年 12 月 8 號,CentOS 官方宣布了停止維護(hù) CentOS Linux 的計(jì)劃,并推出了 CentOS Stream 項(xiàng)目,CentOS Linux 8 作為 RHEL 8 的復(fù)刻版本,生命周期縮短,于 2021 年 12 月 31 日停止更新并停止維護(hù)(EOL),更多的信息可

    2024年02月12日
    瀏覽(21)
  • ES5節(jié)點(diǎn)假死,內(nèi)核日志報(bào)INFO: task blocked for more than 120 seconds.

    es集群里有一臺機(jī)器,突然cpu load飆到 21左右(8core cpu),但是cpu使用率會變成0,且同時(shí)io 等使用率全部變?yōu)?.這種狀態(tài)不可以自己恢復(fù),除非重啟。es沒有判斷出節(jié)點(diǎn)有問題,整個集群不可以訪問,所有操作都超時(shí),包括cat集群信息等接口,直到重啟機(jī)器。這種情況下節(jié)點(diǎn)已

    2024年02月06日
    瀏覽(16)
  • Repository docker-ce-test is listed more than once in the configuration

    這個消息表明,在你的 CentOS 系統(tǒng)的 YUM 軟件源配置中, docker-ce-stable 、 docker-ce-stable-source 和 docker-ce-test 這幾個倉庫被列出了多次。這通常發(fā)生在 /etc/yum.repos.d/ 目錄下的 YUM 配置文件中,相同的倉庫被重復(fù)添加。 這種情況可能不會直接影響你安裝軟件包的能力,但它可能導(dǎo)致

    2024年01月21日
    瀏覽(17)
  • RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface

    RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface

    使用 matplotlib 繪制多幅圖出現(xiàn)如下問題 RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface ( matplotlib.pyplot.figure ) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning). fig, ax = plt.subplots(figsize=(10, 10)) 。

    2024年02月13日
    瀏覽(19)
  • LeetCode --- 1869. Longer Contiguous Segments of Ones than Zeros 解題報(bào)告

    Given a binary string? s , return? true ?if the? longest ?contiguous segment of? 1 \\\' s is? strictly longer ?than the? longest ?contiguous segment of? 0 \\\' s in? s , or return? false ?otherwise . For example, in? s = \\\" 11 01 000 10\\\" ?the longest continuous segment of? 1 s has length? 2 , and the longest continuous segment of? 0 s has length?

    2024年02月15日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包