2010-05-14 152 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 
}