Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntentService won't show Toast

This IntentService I created will show Toasts in onStartCommand() and in onDestroy(), but not in onHandleIntent(). Am I missing something about the limitations of an IntentService?

public class MyService extends IntentService {  private static final String TAG = "MyService";  public MyService(){     super("MyService"); }  @Override protected void onHandleIntent(Intent intent) {     cycle(); }  @Override public int onStartCommand(Intent intent, int flags, int startId) {     Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); //This happens!     return super.onStartCommand(intent,flags,startId); }  @Override public void onCreate() {     super.onCreate();  }  @Override public void onDestroy() {     Toast.makeText(this, "service stopping", Toast.LENGTH_SHORT).show(); //This happens!     super.onDestroy(); }  private void cycle(){       Toast.makeText(this, "cycle done", Toast.LENGTH_SHORT).show();  //This DOESN'T happen!       Log.d(TAG,"cycle completed"); //This happens! } } 
like image 649
Tenfour04 Avatar asked Mar 18 '11 01:03

Tenfour04


1 Answers

The accepted answer is not correct.

Here is how you can show toast from onHandleIntent():

Create a DisplayToast class:

public class DisplayToast implements Runnable {     private final Context mContext;     String mText;      public DisplayToast(Context mContext, String text){         this.mContext = mContext;         mText = text;     }      public void run(){         Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();     } } 

Instantiate a Handler in your service's constructor and call the post method with a DisplayToast object inside.

public class MyService extends IntentService { Handler mHandler;  public MyService(){     super("MyService");     mHandler = new Handler(); }  @Override protected void onHandleIntent(Intent intent) {     mHandler.post(new DisplayToast(this, "Hello World!"));  } } 
like image 112
Jim G. Avatar answered Sep 23 '22 19:09

Jim G.