Is it possible to start an Activity from a Service? If yes, how can we achieve this?
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
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.
Intent i = new Intent(); i.setClass(this, MyActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i);
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0