How to create toast from IntentService? It gets stuck on the screen

Omri picture Omri · Oct 17, 2010 · Viewed 10.6k times · Source

I'm trying to have my IntentService show a Toast message, but when sending it from the onHandleIntent message, the toast shows but gets stuck and the screen and never leaved. I'm guessing its because the onHandleIntent method does not happen on the main service thread, but how can I move it?

Has anyone has this issue and solved it?

Answer

Nathan Schwermann picture Nathan Schwermann · Oct 18, 2010

in onCreate() initialize a Handler and then post to it from your thread.

private class DisplayToast implements Runnable{
  String mText;

  public DisplayToast(String text){
    mText = text;
  }

  public void run(){
     Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
  }
}
protected void onHandleIntent(Intent intent){
    ...
  mHandler.post(new DisplayToast("did something")); 
}