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

Pen*_*m10 27 android toast looper android-asynctask

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

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

我怎样才能做到这一点?

Ale*_*voy 37

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

protected void onProgressUpdate(Integer... progress) {
}
Run Code Online (Sandbox Code Playgroud)

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


Jac*_*ani 24

你可以在doInBackground里面吐司

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

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

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


Ale*_*kov 19

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


小智 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(); 
}
Run Code Online (Sandbox Code Playgroud)