2010-05-14 151 views

回答

35

onPostExecute - 在UI線程上執行 或 publishProgress();在doinbackground和

protected void onProgressUpdate(Integer... progress) { 
} 

http://developer.android.com/reference/android/os/AsyncTask.html

+0

我必須在過程中間發出Toast,而不是結束。我有什麼選擇? – Pentium10 2010-05-14 22:03:00

+0

onProgressUpdate。它也運行在UI線程和Toast應該罰款 – 2010-05-15 21:13:14

+0

-1 downvoted,因爲這個問題的每個其他答案比這個更好! – necromancer 2014-08-22 03:09:47

19

您還可以使用runOnUiThread方法從後臺線程操作你的UI。

+0

爲什麼投票?我認爲他必須調用runOnUiThread。 – 2010-05-14 22:48:56

+1

適合我。只需要調用getActivivty()。runOnUiThread(...) – demula 2013-08-12 10:21:41

1

如果您想從後臺線程顯示Toast,您必須從doInBackground調用runOnUiThread。我不相信有另一種方式。

編輯:我收回。我認爲你可以實現在UI線程上運行的onProgressUpdate來顯示Toast並從doInBackground調用publishProgress。

9

如果你想使用吐司 你應該使用這種方法:onProgressUpdate()

protected Integer doInBackground(Void...Params) { 
    int check_point = 1; 
    publishProgress(check_point); 
    return check_point; 
} 

protected void onProgressUpdate(Integer integers) { 
    if(integers == 1) { 
    Toast.makeText(classname.this, "Text", 0).show(); 
} 
19

可以在裏面doInBackground

添加以下代碼要吐司出現

runOnUiThread(new Runnable() { 
public void run() { 

    Toast.makeText(<your class name>.this, "Cool Ha?", Toast.LENGTH_SHORT).show(); 
    } 
}); 
敬酒
+0

謝謝!這正是我所期待的。 – 2017-03-20 12:22:04

1

如果要在doInBackground中顯示Toast,可以在AsyncTask的OnPostExecute方法中使用它。

protected void onPostExecute(String file_url) {  
    Toast.makeText(getApplicationContext(),"Your Message", Toast.LENGTH_LONG).show(); 

    pDialog.dismiss();//dismiss the progress dialouge 
}