From inside the Service class:
Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:
Intent dialogIntent = new Intent(this, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(dialogIntent);
and in one my subclasses, stored in a separate file I had to:
public static Service myService;
myService = this;
new SubService(myService);
Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);
All the other answers gave me a nullpointerexception
.
UPDATE ANDROID 10 AND HIGHER
Start an activity from service (foreground or background) is no longer allowed.
There are still some restrictions that can be seen in the documentation
https://developer.android.com/guide/components/activities/background-starts
Another thing worth mentioning: while the answer above works just fine when our task is in the background, the only way I could make it work if our task (made of service + some activities) was in the foreground (i.e. one of our activities visible to user) was like this:
Intent intent = new Intent(storedActivity, MyActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
storedActivity.startActivity(intent);
I do not know whether ACTION_VIEW or FLAG_ACTIVITY_NEW_TASK are of any actual use here. The key to succeeding was
storedActivity.startActivity(intent);
and of course FLAG_ACTIVITY_REORDER_TO_FRONT for not instantiating the activity again. Best of luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With