系统相关
首页 > 系统相关> > Android Pie(9.0)WebView在多进程中

Android Pie(9.0)WebView在多进程中

作者:互联网

启动Android Pie(API 28),Google不允许在2个不同的进程中使用单个WebView实例.

文档:https://developer.android.com/reference/android/webkit/WebView.html#setDataDirectorySuffix(java.lang.String)

根据需要,我调用了WebView.setDataDirectorySuffix(“dir_name_no_separator”)但不幸的是,我得到了一个例外.
我试图在第二个进程Service onCreate()中调用此方法.

java.lang.RuntimeException: Unable to create service com.myapp.service.MyService: java.lang.IllegalStateException: Can't set data directory suffix: WebView already initialized
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3544)
        at android.app.ActivityThread.access$1300(ActivityThread.java:199)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1666)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.IllegalStateException: Can't set data directory suffix: WebView already initialized
        at android.webkit.WebViewFactory.setDataDirectorySuffix(WebViewFactory.java:136)
        at android.webkit.WebView.setDataDirectorySuffix(WebView.java:2165)
        at com.myapp.service.MyService.onCreate(MyService.java:134)

我找不到任何理由这个例外.我没有两次调用这个方法,也没有在主进程中调用它.有任何想法吗?

解决方法:

解决了.

我的项目托管了AdMob广告,我在Application类onCreate()中调用了MobileAds.initialize()方法.广告初始值设定项会加载一个WebView,在调用WebView.setDataDirectorySuffix(“dir_name_no_separator”)方法之前,该WebView现在禁止在新进程中执行.

当创建第二个进程时,它也会通过相同的应用程序创建流,这意味着它在Application类中调用相同的onCreate(),它调用尝试创建新WebView实例的MobileAds.initialize()并由此引起碰撞.

IllegalStateException: Can't set data directory suffix: WebView already initialized

我怎么解决这个问题?

我使用下面的方法获取进程名称,并检查它是否是我的主进程 – 调用MobileAds.initialize()方法,如果这是我的第二个进程,请调用
WebView.setDataDirectorySuffix(“dir_name_no_separator”)方法.

获取进程名称:

public static String getProcessName(Context context) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
        if (processInfo.pid == android.os.Process.myPid()) {
            return processInfo.processName;
        }
    }

    return null;
}

应用程序类onCreate():

if (!Utils.getProcessName(this).equals("YOUR_SECOND_PROCESS_NAME")) {
    MobileAds.initialize(this);
} else {
    WebView.setDataDirectorySuffix("dir_name_no_separator")
}

标签:android-9-0-pie,android,android-service,multiprocessing
来源: https://codeday.me/bug/20191005/1855383.html