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!
}
}
onHandleIntent() is called from a background thread (that is what IntentService is all about), so you shouldn't do UI from there.
Another option is RxJava, e.g.:
Caveat: I'm new to Android.
You should start the Toast on the main thread:
This is because otherwise the thread of the IntentService quits before the toast can be send out, causing a IllegalStateException:
The accepted answer is not correct.
Here is how you can show toast from
onHandleIntent()
:Create a DisplayToast class:
Instantiate a
Handler
in your service's constructor and call thepost
method with aDisplayToast
object inside.