Android clear webview thread, free memory, avoid OutOfMemoryError

僤鯓⒐⒋嵵緔 提交于 2019-12-03 12:03:00

Okay, so the conclusion to this issue was that the String buffer could not be predetermined or properly cleared at these file sizes.

In this case the image was pulled from a server as a string, manipulated as a string and finally displayed as an image.

Whether displayed as an ImageView or as a Webview, it did not matter, the app would crash once a string buffer became full (which it would not clear no matter how much stuff I freed or set to null), This was an encryption effort.

but Finally just settled with storing the images in the app's assets folder.

hwrdprkns

Maybe try recycling the bitmap/image?

If that doesn't work, I suggest re-sampling it.

Strange out of memory issue while loading an image to a Bitmap object

Efficient way ever:

WebViewActivity.java

public class WebViewActivity extends AppCompatActivity {

    private WebView mWebView;
    private RelativeLayout mWebViewParent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mWebViewParent = (RelativeLayout) findViewById(R.id.layoutWebViewParent);
        mWebView = (WebView)findViewById(R.id.webView);

        // Other stuff

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyWebView();
    }

    private void destroyWebView() {
        mWebViewParent.removeAllViews();
        if(mWebView != null) {
            mWebView.clearHistory();
            mWebView.clearCache(true);
            mWebView.loadUrl("about:blank");
            mWebView.freeMemory();
            mWebView.pauseTimers();
            mWebView = null;
        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}

activity_web_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutWebViewParent" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </WebView>

</RelativeLayout>

AndroidManifest.xml

<activity
    android:name=".WebViewActivity"
    android:label="@string/title_activity_web_view"
    android:process="webview.kill">
</activity>

Hope this will help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!