I'm currently developing an application that features a WebView
running JavaScript code. This particular JavaScript code tends to be memory-intensive and can sometimes exceed the allotted memory, leading to crashes in the WebView's Chromium process and ultimately causing my app to crash.
Despite implementing listeners for onMemoryTrim
in my app, I've noticed that it is not triggered on devices with more than 1GB of memory, even when reaching TRIM_MEMORY_RUNNING_LOW
.
My main concern now is finding a way to detect when the WebView is running low on memory so that I can either terminate it or prompt it to free up memory. I attempted to monitor memory usage using performance.memory
, but this approach was unsuccessful as executing a similar script within the WebView resulted in crashes:
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 a reliable method to anticipate when memory is about to be exhausted so that I can address this issue proactively and prevent app crashes?