如何在AsyncTask中举起一个toast,我被提示使用Looper

时间:2010-05-14 21:13:29

标签: android android-asynctask toast looper

我在后台完成了AsyncTask完成的任务。在某些时候,我需要发出一个完成某事的Toast。

我尝试过但我失败了因为 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我该怎么做?

6 个答案:

答案 0 :(得分:37)

onPostExecute - 在UI线程上执行 要么  publishProgress();在你的doinbackground和

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

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

答案 1 :(得分:23)

你可以在doInBackground里面吐司

将此代码添加到要显示Toast的位置

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

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

答案 2 :(得分:19)

您还可以使用runOnUiThread方法从后台线程操作UI。

答案 3 :(得分:9)

如果你想使用Toast 您应该使用此方法: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(); 
}

答案 4 :(得分:1)

如果要从后台线程显示Toast,则必须从doInBackground调用runOnUiThread。我不相信还有另一种方式。

编辑:我接受了。我认为您可以实现在UI线程上运行的onProgressUpdate,以显示Toast并从doInBackground调用publishProgress。

答案 5 :(得分: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
}