1

I have a toast in a slave thread which needs to tell a user wen a connection is established. To do this I know I need to use Async to make the toast happen, but I'm not sure where or how to implements the extended async. If I understand it, I think I can just create a MyAsync with the and just onProgressUpdate() the toast?

@Override
public void onProgressUpdate(String... args) {

         Toast.makeText(context, args, Toast.LENGTH_SHORT).show();
}

Thanks for your time ~Aedon

Cristian
  • 198,401
  • 62
  • 356
  • 264
ahodder
  • 11,353
  • 14
  • 71
  • 114

1 Answers1

1

Yep, you should be able to just extend the ASyncTask and change the template variables to what you need. The Toast class is a static class so it can be called from any thread without worrying about conflicts.

I don't see any issues with your code above except you wouldn't want to be calling new Toast messages very often since they stack. So if you were to continuous call the .show() function it would stack them and continue to show new Toast messages every LENGTH_SHORT interval until it caught up.

As for an example of an ASyncTask, here you go:

private class MyAsync extends AsyncTask<<What to pass in to doInBackground>, <What to pass in to onProgressUpdate>, <What type onPostExecute receives>> {
     protected T (result type to onPostExecute) doInBackground(T... urls) {
         //Do big calculations in here
     }

     protected void onProgressUpdate(T... progress) {
         //Update
     }

     protected void onPostExecute(T result) {
         //Done
     }
 }
SpencerElliott
  • 885
  • 5
  • 16
  • I'm not sure what placing a Toast message in onProgressUpdate will do. If the OP has problems, see this question: http://stackoverflow.com/questions/4209814/posting-toast-message-from-a-thread (this is using Thread and not AsyncTask, but you can still talk to the ui thread in the same way – Andrew Nov 29 '10 at 17:32
  • kk ty much. All I do to make the toast is new MyAsync().execute(mContext, aString, void); and it is toasted? – ahodder Nov 29 '10 at 17:44
  • If you just want to show a Toast message and not do any other processing in the AsyncTask you can just call Toast.makeText(...).show() in your UI thread since it's non-blocking. No need to make a full thread just to show a Toast message. – SpencerElliott Nov 29 '10 at 17:49