之前遇到webview空指针问题,调查了一下源码,追述到webviewCore
原来在webview执行destory之后,webviewCore会被置为null,而这时候我们的webview仍然没有任何的迹象,所以我们仍然大胆地使用webview,在执行到loadUrl或者stopLoading等方法时,由于webviewCore已经为null,这时就产生了空指针,异常信息如下:
03-01 10:58:21.117: E/AndroidRuntime(13295): java.lang.NullPointerException 03-01 10:58:21.117: E/AndroidRuntime(13295): at android.webkit.WebView.stopLoading(WebView.java:2202) 03-01 10:58:21.117: E/AndroidRuntime(13295): at com.tiantianmini.android.browser.ui.download.DownloadListener.onDownloadStart(DownloadListener.java:119) 03-01 10:58:21.117: E/AndroidRuntime(13295): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:405) 03-01 10:58:21.117: E/AndroidRuntime(13295): at android.os.Handler.dispatchMessage(Handler.java:99) 03-01 10:58:21.117: E/AndroidRuntime(13295): at android.os.Looper.loop(Looper.java:137) 03-01 10:58:21.117: E/AndroidRuntime(13295): at android.app.ActivityThread.main(ActivityThread.java:4340) 03-01 10:58:21.117: E/AndroidRuntime(13295): at java.lang.reflect.Method.invokeNative(Native Method) 03-01 10:58:21.117: E/AndroidRuntime(13295): at java.lang.reflect.Method.invoke(Method.java:511) 03-01 10:58:21.117: E/AndroidRuntime(13295): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-01 10:58:21.117: E/AndroidRuntime(13295): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-01 10:58:21.117: E/AndroidRuntime(13295): at dalvik.system.NativeStart.main(Native Method)为了避免该问题,我们有两种途径:
1.使用类似loadUrl等方法时,捕获异常信息
2.自定义类继承webview,当调用webview的destory方法之后,使用变量保存destroy的状态,在用到类似loadUrl方法之前判断是否已经destroy
代码类似于
@Override public void destroy() { this.isDestroy = true; super.destroy(); } @Override public void loadUrl(String url, Map<String, String> extraHeaders) { if(this.isDestroy == true){ return ; } super.loadUrl(url, extraHeaders); }