How to display a Toast in Android AsyncTask?
This is another way which is not mentioned here as follows:
Step 1: Define Handler as global
Handler handler;
Step 2: Initialise handler in doInBackground() method as follows:
@Override
protected Void doInBackground(Void... params) {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
//your code
}
}
};
}
Step 3: And now you can call that handler by anywhere in code by calling
if(handler != null){
handler.sendEmptyMessage(1);
}
What more you can do is you can send data through handler as follows:
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putInt("KEY", value);
message.setData(bundle);
handler.sendMessage(message);
And handle data in you handler as below
handler = new Handler(){
@Override
public void handleMessage(Message message) {
Bundle bundle = message.getData();
Integer value = bundle.getInt("KEY");
}
};
You cannot update UI on background thread. doInBackground()
is invoked on the background thread. You should update UI on the UI thread.
runOnUiThread(new Runnable(){
@Override
public void run(){
//update ui here
// display toast here
}
});
onPreExecute()
, onPostExecute(Result)
, are invoked on the UI thread. So you can display toast here.
onProgressUpdate(Progress...)
, invoked on the UI thread after a call to publishProgress(Progress...)
can be used to animate a progress bar or show logs in a text field.
The result of doInBackground()
computation is a parameter to onPostExecute(Result)
so return the result in doinBackground()
and show your toast in onPostExecute(Result)
You can also use a handler as suggested by @Stine Pike
For clarity, check the link below under the topic: The 4 steps.
http://developer.android.com/reference/android/os/AsyncTask.html
Create a handler object and execute all your Toast messages using that.
@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();
}
});
}