最近在activity嵌套webview顯示大量圖文發現APP內存一直在漲,沒法釋放內存,查了很多資料,大概是webview的一個BUG,引用了activity導致內存泄漏,所以就嘗試傳遞getApplicationContext。
1.避免在xml直接寫webview控件,這樣會引用activity,所以在xml寫一個LinearLayout,然后 linearLayout.addView(new MyWebview(getApplicationContext()));
這樣動態生成webview就能避免內存泄漏,可是這樣會導致部分機型的webview里面點擊超鏈接會出現異常,程序崩潰,暫時的解決辦法是禁止點擊,需要重寫webview,
public class MyWebview extends WebView { public MyWebview(Context context) { super(context); } public MyWebview(Context context, AttributeSet attrs) { super(context, attrs); } public MyWebview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean onTouchEvent(MotionEvent event) { return false; } }
這樣能避免出現程序崩潰。
2.activity關閉時需要手動釋放webview內存
@Override protected void onDestroy() { super.onDestroy(); if(webview_projectinfo != null){ webview_projectinfo.removeAllViews(); webview_projectinfo.destroy(); webview_projectinfo = null; ll_webview.removeAllViews(); ll_webview = null; } }
上面的方法 已經可以把內存釋放出來,但是有缺陷,就是沒法點擊webview的內容,還有一種方法是給嵌套webview的activity另開一個進程,作為一個獨立進程展示。