解决:Android出现All WebView methods must be called on the same thread.

解决:Android出现All WebView methods must be called on the same thread.

13401发表于2016-01-26

今天用Android做了一个下拉WebView当前页面出现了下面异常:

01-26 14:00:08.000: W/WebView(32573): java.lang.Throwable: A WebView method was called on thread 'AsyncTask #1'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2d32c547} called on null, FYI main Looper is Looper (main, tid 1) {2d32c547})

01-26 14:00:08.000: W/WebView(32573): at android.webkit.WebView.checkThread(WebView.java:2209)
01-26 14:00:08.000: W/WebView(32573): at android.webkit.WebView.getUrl(WebView.java:1305)
01-26 14:00:08.000: W/WebView(32573): at com.example.demo1.RefreshActivity$1.onRefresh(RefreshActivity.java:39)
01-26 14:00:08.000: W/WebView(32573): at com.example.demo1.RefreshableView$RefreshingTask.doInBackground(RefreshableView.java:430)
01-26 14:00:08.000: W/WebView(32573): at com.example.demo1.RefreshableView$RefreshingTask.doInBackground(RefreshableView.java:1)
01-26 14:00:08.000: W/WebView(32573): at android.os.AsyncTask$2.call(AsyncTask.java:292)
01-26 14:00:08.000: W/WebView(32573): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-26 14:00:08.000: W/WebView(32573): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-26 14:00:08.000: W/WebView(32573): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-26 14:00:08.000: W/WebView(32573): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-26 14:00:08.000: W/WebView(32573): at java.lang.Thread.run(Thread.java:818)


原来新版的Android的SDK要求在创建WebView所在的线程中操作它,在其它线程中操作它都会报这个错误。

解决办法:


RefreshActivity.this.runOnUiThread(new Runnable() {
	@Override
	public void run() {
		webview.loadUrl("http://www.lanhusoft.com");  
	}
});


RefreshActivity就是webview所在的Activity。


webview是通过webview = (WebView) findViewById(R.id.webViewLanhu);获取到的对象实例。


小编蓝狐