我的任務由AsyncTask在後臺完成。在某些時候,我需要發佈Toast來完成一些事情。如何在AsyncTask中舉杯祝酒,系統提示我使用Looper
我試過,我失敗了,因爲 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我怎麼能這樣做?
我的任務由AsyncTask在後臺完成。在某些時候,我需要發佈Toast來完成一些事情。如何在AsyncTask中舉杯祝酒,系統提示我使用Looper
我試過,我失敗了,因爲 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我怎麼能這樣做?
onPostExecute - 在UI線程上執行 或 publishProgress()
;在doinbackground和
protected void onProgressUpdate(Integer... progress) {
}
http://developer.android.com/reference/android/os/AsyncTask.html
您還可以使用runOnUiThread方法從後臺線程操作你的UI。
爲什麼投票?我認爲他必須調用runOnUiThread。 – 2010-05-14 22:48:56
適合我。只需要調用getActivivty()。runOnUiThread(...) – demula 2013-08-12 10:21:41
如果您想從後臺線程顯示Toast,您必須從doInBackground調用runOnUiThread。我不相信有另一種方式。
編輯:我收回。我認爲你可以實現在UI線程上運行的onProgressUpdate來顯示Toast並從doInBackground調用publishProgress。
如果你想使用吐司 你應該使用這種方法: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();
}
可以在裏面doInBackground
添加以下代碼要吐司出現
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(<your class name>.this, "Cool Ha?", Toast.LENGTH_SHORT).show();
}
});
敬酒
謝謝!這正是我所期待的。 – 2017-03-20 12:22:04
如果要在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
}
我必須在過程中間發出Toast,而不是結束。我有什麼選擇? – Pentium10 2010-05-14 22:03:00
onProgressUpdate。它也運行在UI線程和Toast應該罰款 – 2010-05-15 21:13:14
-1 downvoted,因爲這個問題的每個其他答案比這個更好! – necromancer 2014-08-22 03:09:47