如何在Android AsyncTask中显示Toast?

时间:2013-05-30 07:22:23

标签: android android-asynctask toast

我正在尝试在使用AsyncTask<URL, Integer, Long>扩展的initial_background类中显示Toast。我在logcat中收到此错误。

public class InitialBackgroundTask extends AsyncTask<URL, Integer, Long> {

    @Override
    protected Long doInBackground(URL... params) {
        // TODO Auto-generated method stub
        show a = new show();
        a.loop();
        return null;
    }

public class show {

    void loop()
    {
        for(int i=0; i<10; i++)
        {
            Toast.makeText(MainActivity.me, "test", Toast.LENGTH_LONG).show();
        }
    }
}

这是一个例外:

05-30 12:08:12.641: E/AndroidRuntime(30840): FATAL EXCEPTION: AsyncTask #1
05-30 12:08:12.641: E/AndroidRuntime(30840): java.lang.RuntimeException: An error occured while executing doInBackground()
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.lang.Thread.run(Thread.java:856)
05-30 12:08:12.641: E/AndroidRuntime(30840): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.os.Handler.<init>(Handler.java:121)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.widget.Toast$TN.<init>(Toast.java:317)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.widget.Toast.<init>(Toast.java:91)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.widget.Toast.makeText(Toast.java:233)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at   com.example.toast.show.loop(show.java:11)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at com.example.toast.InitialBackgroundTask.doInBackground(InitialBackgroundTask.java:13)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at com.example.toast.InitialBackgroundTask.doInBackground(InitialBackgroundTask.java:1)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
05-30 12:08:12.641: E/AndroidRuntime(30840):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-30 12:08:12.641: E/AndroidRuntime(30840):    ... 5 more

以上代码展示了整个故事。实际上,我想在doInBackground方法中显示吐司

8 个答案:

答案 0 :(得分:27)

您无法在后台线程上更新UI。在后台线程上调用doInBackground()。您应该在UI线程上更新UI。

      runOnUiThread(new Runnable(){

          @Override
          public void run(){
            //update ui here
            // display toast here 
          }
       });
在UI线程上调用

onPreExecute()onPostExecute(Result)。所以你可以在这里展示吐司。

调用onProgressUpdate(Progress...)后在UI线程上调用的

publishProgress(Progress...)可用于为进度条设置动画或在文本字段中显示日志。

doInBackground()计算的结果是onPostExecute(Result)的参数,因此请在doinBackground()中返回结果并在onPostExecute(Result)

中显示您的祝酒词

您也可以使用@Stine Pike建议的处理程序

为清楚起见,请查看以下主题下的链接: 4个步骤

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

答案 1 :(得分:22)

创建一个处理程序对象并使用它执行所有Toast消息。

@Override
protected Void doInBackground(Void... params) {
    Handler handler =  new Handler(context.getMainLooper());
    handler.post( new Runnable(){
        public void run(){
            Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show(); 
        }
    });
  }

答案 2 :(得分:4)

这是另一种方法,这里没有提到如下:

第1步:处理程序定义为全局

Handler handler;

第2步: doInBackground()方法中初始化处理程序,如下所示:

@Override
protected Void doInBackground(Void... params) {
    Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 1) {
           //your code
        }
    }
  };
}

第3步:    现在,您可以通过调用

在代码中的任何位置调用该处理程序
if(handler != null){
  handler.sendEmptyMessage(1);
}
  

您可以做的更多事情是您可以通过处理程序发送数据,如下所示:

Message message = new Message();
Bundle bundle = new Bundle();
bundle.putInt("KEY", value);
message.setData(bundle);
handler.sendMessage(message);

并处理您在处理程序中的数据,如下所示

handler = new Handler(){ 
    @Override
    public void handleMessage(Message message) {
        Bundle bundle = message.getData();
        Integer value = bundle.getInt("KEY");

    }
};

答案 3 :(得分:2)

在onPostExecute或onPreExecute中显示你的Toast。 doInBackGround在一个单独的线程上运行,但另外两个方法在UI线程上运行。

但如果必须在doInBackGround中显示吐司,那么您可以使用Handler.postrunonUiThread来执行吐司。

答案 4 :(得分:2)

您无法在非UI线程中显示Toast(即在后台执行)。您可以尝试使用标记概念。

public class HttpRequest extends AsyncTask<String[], Void, String> {
    boolean flag=false;
....
...
....
 @Override
    protected String doInBackground(String[]... params) {
   //set flag as true when you need to trigger the Toast
 try{
   //Some Network Calls
     } catch (HttpHostConnectException e) {
    flag=true;   
  //Triggered Flas when i got Exceptions          
       }
}
 @Override
    protected void onPostExecute(String result) {
        if(flag){
            Toast.makeText(activity, "HttpHostConnectException Occured ", Toast.LENGTH_SHORT).show();
        }


}

快乐编码.. !!!在这里输入代码

答案 5 :(得分:0)

你试图在非ui线程中显示toast,这就是为什么会出现这个错误。

如果你想在doInBackground方法中显示toast,那么你必须在UI线程中编写Toast逻辑

看看下面的回答链接 https://stackoverflow.com/a/11797945/582571

但不建议在非ui线程下进行UI操作

答案 6 :(得分:0)

我们可以通过将接口传递给AsyncTask类并在 onPostExecute 方法中进行回调来实现。

public interface IResult {
    void onSuccess(String result);
    void onError(String error);                                                  
}

public static class AsyncTaskClass extends AsyncTask<String, String, Boolean> {

    IResult iResult;

    AsyncTaskClass(IResult iResult){
        this.iResult = iResult;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        boolean result;
        try {
            //doing BackGround Operation Here
            result = true;

        } catch (Exception e) {
            Log.e(TAG,"Error: " + e.getMessage());
            result = false;
        }

       return result;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        super.onPostExecute(success);
        Log.w(TAG, "On Post Execute: " + success);
        if(success)
            iResult.onSuccess("AsyncTask done successfully.");
        else
            iResult.onSuccess("Sorry! something went wrong.");

    }
}                                                                      
  IResult iResult = new IResult() {
      @Override
      public void onSuccess(String result) {
          Toast.makeText(PostActivity.this, result, Toast.LENGTH_LONG).show();
      }

      @Override
      public void onError(String error) {
          Toast.makeText(PostActivity.this, error, Toast.LENGTH_LONG).show();
      }
  };
  String param1 = "some value 1";
  String param2 = "some value 2";

  new AsyncTaskClass(iResult).execute(param1, param2);`

答案 7 :(得分:0)

使用SDK 29

public class LoginControl extends AsyncTask<String, Void, String> {
    private final Context context;

    public LoginControl (Context context) {
        this.context = context;
    }
    
    @Override
    protected String doInBackground(String... strings) {
     //do something
    }

    @Override
    protected void onPostExecute(TokenBean tokenBean) {
       Toast.makeText(context, "hello Toast", Toast.LENGTH_SHORT).show();
    }
}

在MainActivity.class

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String url="something";
        Context context = getApplicationContext();
        new LoginControl(context).execute(url);
    }