How to start an Activity from a Service?

Is it possible to start an Activity from a Service? If yes, how can we achieve this?


android.app.Service is descendant of android.app.Context so you can use startActivity directly. However since you start this outside any activity you need to set FLAG_ACTIVITY_NEW_TASK flag on the intent.

For example:

Intent i = new Intent();
i.setClass(this, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

where this is your service.


Even if the framework allows you to start an Activity from a Service, it's probably not a proper solution. The reason is that the Service task may or may not be the focus of the user at the time the Service wishes to interact with the user. Interrupting what the user is currently doing is considered bad design form, especially from something that is supposed to be operating in the background.

Therefore, you should consider using a Notification with Notification Service, which carries a PendingIntent to launch the desired Activity when the user decides it is time to investigate. Think of it as delayed gratification.


I had a problem starting an activity from a service, it was due to the missing FLAG_ACTIVITY_NEW_TASK intent flag.


This surely will solve your problem

Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ComponentName cn = new ComponentName(this, TaxiPlexer.class);
intent.setComponent(cn);
startActivity(intent);