如何在doInBackground中的AsyncTask中显示toast

rei*_*ley 13 android android-asynctask

在我正在使用的一项活动中AsyncTask.在doInBackground()我做各种方法的调用.在其中一个方法中我得到一个异常,所以在catch块中我想在Toast中显示错误.我知道我可以使用Log,但我仍然喜欢Toast.那么,如何在doInBackground()中的AsyncTask中使用Toast?

Rob*_*der 17

从doInBackground返回为

protected String doInBackground(String... params){
    //some code
    try{
       //some code
     }catch(Exception e){
        return "Exception Caught";
     }
     return someValidResult;
}

protected void onPostExecute(String result){
    if(result.equalsIgnoreCase("Exception Caught")){
       //Display Toast
    }else{
       // // whatever you wana do with valid result
    }
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*Sam 11

你可以把Toast包裹起来,runOnUIThread()但这不是最好的解决方案.
当发生错误时,则应该设置在catch块一个布尔标志,然后显示在适当的吐司onProgressUpdate(),onPostExecute()或任何与UI访问的其它方法,只要该标志为true.


Har*_*d07 6

编写以下代码,您必须在doInBackground()方法中显示toast

runOnUiThread(new Runnable() {

public void run() {

  Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();

   }
});
Run Code Online (Sandbox Code Playgroud)
  • 顺便说一句:如果你正在使用Fragments,你需要runOnUiThread(...)通过你的活动来打电话:

getActivity().runOnUiThread(...)