How to raise a toast in AsyncTask, I am prompted to used the Looper

99封情书 提交于 2019-11-26 09:47:12

问题


I have tasks completed by AsyncTask in background. At some point I need to issue a Toast that something is completed.

I\'ve tried and I failed because Caused by: java.lang.RuntimeException: Can\'t create handler inside thread that has not called Looper.prepare()

How can I do that?


回答1:


onPostExecute - executes on UI thread or publishProgress(); in your doinbackground and

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

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




回答2:


you can Toast inside doInBackground

add this code where you want to Toast appear

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

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



回答3:


You can also use runOnUiThread method to manipulate your UI from background threads.




回答4:


If you want to use Toast You should use this method : 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(); 
}



回答5:


If you want to display the Toast from the background thread you'll have to call runOnUiThread from doInBackground. I don't believe there's another way.

Edit: I take that back. I think you can implement onProgressUpdate, which runs on the UI thread, to show the Toast and make calls to publishProgress from doInBackground.




回答6:


If you want to display the Toast in doInBackground, you can use it in the OnPostExecute method of AsyncTask.

protected void onPostExecute(String file_url) {    
   Toast.makeText(getApplicationContext(),"Your Message", Toast.LENGTH_LONG).show();

   pDialog.dismiss();//dismiss the progress dialouge
}


来源:https://stackoverflow.com/questions/2837676/how-to-raise-a-toast-in-asynctask-i-am-prompted-to-used-the-looper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!