检测WebView内部的可用内存 [英] Detect available memory inside of a WebView

查看:209
本文介绍了检测WebView内部的可用内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个包含运行JavaScript代码的 WebView 的应用程序。 JavaScript代码的分配量非常大,并且可能需要大量内存。



有时候,所需内存的数量超过了JavaScript可能需要的数量,并且崩溃了Chromium进程在我的应用程序中监听 onMemoryTrim - 但在此场景中永远不会调用它

在具有超过1GB内存的设备上。 (甚至没有 TRIM_MEMORY_RUNNING_LOW )。

有什么方法可以检测到我的WebView内存不足,要么杀了它,要么让它知道(这样它可以释放内存)?

我试过轮询 performance.memory ,但没有奏效。下面的脚本会在WebView中执行时崩溃:

  var a = []; 

var kek =()=> {
var b = []; (var i = 0; i <1024 * 1024 * 2; i ++)b.push(Math.random());

return b;
}

var ival = setInterval(()=> {
let m = performance.memory;
if(m.jsHeapSizeLimit - m.usedJSHeapSize< 1e5){
console.log(Memory limited)
} else {
.push(kek());
}
});

是否有任何方法可以检测内存即将耗尽,所以我可以在没有应用程序的情况下正常处理它崩溃?

解决方案

我已经与Chromium团队和Android团队讨论过这个问题,他们现在(他们认为我相信他们) 这是不可能的


有时,所需的内存量超过了JavaScript可能需要的数量并导致Chromium您可以使用 https://developer.android.com/preview/features/managing-webview.html#termination-handlerel =noreferrer>新的终止句柄API 。所以这可以解决我的问题,不必首先检查可用的内存。

通过重写 onRenderProcessGone

> - 我们得到错误并重新创建WebView。


I'm building an app that contains a WebView that runs some JavaScript code. That JavaScript code is quite allocation heavy and can require a lot of memory.

Sometimes, the amount of required memory exceeds the amount JavaScript can require and crashes the Chromium process of the WebView which crashes my app.

I listen to onMemoryTrim in my application - but it is never called in this scenario on devices with more than 1GB of memory. (Not even with TRIM_MEMORY_RUNNING_LOW).

Is there any way I could detect my WebView is running low on memory and either kill it or let it know (so it can free memory)?

I've tried polling performance.memory but it did not work. The following script crashes the WebView if executed in it:

var a = [];

var kek = () => {
  var b = [];
  for(var i = 0; i < 1024 * 1024 * 2; i++) b.push(Math.random());
  return b;
}

var ival = setInterval(() => {
  let m = performance.memory;
  if(m.jsHeapSizeLimit - m.usedJSHeapSize < 1e5) {
    console.log("Memory limited")
  } else {
    a.push(kek());
  }
});

Is there any way to detect memory is about to run out so I can handle it gracefully without the app crashing?

解决方案

I have discussed this with the Chromium team and the Android team and at the moment (they think and I believe them) that this is impossible.

Sometimes, the amount of required memory exceeds the amount JavaScript can require and crashes the Chromium process of the WebView which crashes my app.

You can however catch out of memory crashes in Android 8.0+ using the new termination handle API. So this works around my problem by not having to check the available memory required in the first place.

By overriding onRenderProcessGone - we get to catch the bug and recreate the WebView.

这篇关于检测WebView内部的可用内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆