2014-04-06 41 views

回答

3

您應該使用execute方法啓動ASynctask。

隨着你的代碼,你只需在主線程中調用該方法。 execute將爲Asynctask創建一個新線程。

public void initWebView(String link) { 
    ThreadParse parse = new ThreadParse(); 
    parse.execute(link); 
} 

如果你真的需要做一些在doInBackground的UI,你應該使用runOnUIThread

我抽放這個代碼塊爲例

catch (IndexOutOfBoundsException ex){ 
    currentPage = 1; 
    totalPages = 1; 
    Toast.makeText(Thread.this, "You are on " + currentPage + " of " + totalPages, Toast.LENGTH_LONG).show(); 
    webview.loadDataWithBaseURL("http://netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css", e.html(), "text/html", "utf-8", null); 
    return; 
} 

這裏,讓它工作,你應該做

catch (IndexOutOfBoundsException ex){ 
    YourTopActivity.this.runOnUiThread(new Runnable() 
    { 
     currentPage=1; 
     totalPages=1; 
     Toast.makeText(Thread.this,"You are on "+currentPage+" of "+totalPages,Toast.LENGTH_LONG). 

     show(); 

     webview.loadDataWithBaseURL("http://netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css",e.html(),"text/html","utf-8",null); 
    }); 
    return; 
} 

與用於UI元素的其他內容相同。

runOnUiThread文檔。

這裏YourTopActivity是需要的因爲你應該使用runOnUiThread方法Activity和你在Asynctask類裏面。

無論如何,你應該重新考慮你的代碼中使用onPostExecuteonPreExecute

+0

當我嘗試了,我得到了一個「產生的原因:了java.lang.RuntimeException:無法創建內螺紋已不叫尺蠖處理程序。準備()「錯誤,當我試圖做一個吐司。 – user2833131

+1

這是由於您無法從其他線程編輯UI所致。每次你需要使用UI使用runOnUIThread(或更好的,使用在UI線程中調用的onPostExecute/onPreExecute) –

+0

不,我使用2.3或更高版本。你能給我一個如何使用runOnUIThread的例子嗎?沒有那種Android的經驗。 – user2833131