Android 解决WebView多进程崩溃的方法

问题

在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/558377

1 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多进程崩溃的资料请关注我们其它相关文章!

(0)

相关推荐

  • Android webView如何输出自定义网页

    这次来使用webview输出网页型数据.因为这样的数据好使用富文本编辑器,有各种各样的拓展. 上代码: package controller.hzl.com.testcall; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.We

  • Android中webView加载H5绑定cookie实例

    简介: 我最近在做项目的时候遇到了这种情况: 1.需要用WebView实现一个H5的登陆注册. 2.大赛报名,用H5实现.这些情况下,我需要把cookie传给服务器,让其判断当前账户是否登陆成功.查阅了一些资料后,终于搞定了. 1. 给一个加载的链接设置cookie private void syncCookie(String url) { try { CookieSyncManager.createInstance(mWvSignUp.getContext());//创建一个cookie管理器

  • 解决Android webview设置cookie和cookie丢失的问题

    Android页面嵌套了一个h5,H5页面内部有用户登陆页面,发现h5页面的登陆功能无法使用,一直登陆失败.和web那边商量一会,发现js写入的cookie丢失了.所有需要Android这边在重写写入一次. mWebView = view.findViewById(R.id.mall_view); settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setLoadsImagesAutom

  • Android webView字体突然变小的原因及解决

    背景 最近,端内在做 webView 统一的时候,个性签名中的 WebView 替换为 CustomWebView 之后,发现字体突然变小. 一开始不知道是什么原因,通过二分法查找最近的提交,排查之后,发现是 SignatureWebView 的继承关系从 WebView 修改为 CustomWebView.revert 之后就正常了. 于是,我问自己,为什么会这样呢? 原因分析 我们知道,WebViewSetting 里面是可以修改 WebView 的一些默认设置的. 阅读官方文档,发现 se

  • Android 中 WebView 的基本用法详解

    加载 URL (网络或者本地 assets 文件夹下的 html 文件) 加载 html 代码 Native 和 JavaScript 相互调用 加载网络 URL webview.loadUrl(https://www.baidu.com/); 加载 assets 下的 html 文件 webview.loadUrl(file:///android_asset/test.html); 加载 html 代码 // 两个代码差不多 // 偶尔出现乱码 webview.loadData(); // 比

  • 在Android环境下WebView中拦截所有请求并替换URL示例详解

    需求背景 接到这样一个需求,需要在 WebView 的所有网络请求中,在请求的url中,加上一个xxx=1的标志位. 例如 http://www.baidu.com 加上标志位就变成了 http://www.baidu.com?xxx=1 寻找解决方案 从 Android API 11 (3.0) 开始,WebView 开始在 WebViewClient 内提供了这样一条 API ,如下: public WebResourceResponse shouldInterceptRequest(Web

  • Android webview注入JS代码 修改网页内容操作

    今天开发的时候遇到一个需求,就是需要隐藏webview的元素,鼓捣了半天 在stack overFlow找到了解决办法 在此记录一下 final WebView webview = (WebView)findViewById(R.id.browser); webview.getSettings().setJavaScriptEnabled(true); webview.setWebViewClient(new WebViewClient() { @Override public void onP

  • 详解Android WebView监听console错误信息

    根据需求,我们要拿到h5的错误信息,并将error信息进行上报.查询了下Android WebView的API发现了WebChromeClient这个方法可以满足要求: @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { //获取log的级别 switch (consoleMessage.messageLevel()){ case ERROR://将error信息上报到服务端 LogUtil.log

  • Android实现WebView点击拦截跳转原生

    1. 首先设置Web视图 webview.setWebViewClient(new MyWebViewClient()); webview1.setWebViewClient(new MyWebViewClient()); 2. 拦截点击的链接,跳转到对应的页面 // 监听 所有点击的链接,如果拦截到我们需要的,就跳转到相对应的页面. private class MyWebViewClient extends WebViewClient { @Override public boolean sh

  • Android WebView通过动态的修改js去拦截post请求参数实例

    需求背景: 需要在用户点击提交按钮的时候拦截用户提交的数据. 遇到的问题: 1.页面不是自家前端做的,不能修改网页中的代码 2.要拦截的请求不是get请求,而是一个post请求 (难点在于:如果拦截的请求是get请求的话,我只需要拿到url,将后面拼接的参数键值对取出来就好了,但是post请求的参数键值对我们是看不到的...) 解决重点: 重写webViewClient的shouldInterceptRequest这个方法 1.这个方法是API21以后才出现的,还有一个过时的方法也要重写,不要忘

随机推荐