IntentService won't show Toast
The accepted answer is not correct.
Here is how you can show toast from onHandleIntent()
:
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();}@Overrideprotected void onHandleIntent(Intent intent) { mHandler.post(new DisplayToast(this, "Hello World!"));}}
You should start the Toast on the main thread:
new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); }});
This is because otherwise the thread of the IntentService quits before the toast can be send out, causing a IllegalStateException:
java.lang.IllegalStateException: Handler (android.os.Handler) {12345678} sending message to a Handler on a dead thread
onHandleIntent() is called from a background thread (that is what IntentService is all about), so you shouldn't do UI from there.