'startactivity called from non-activity contex

2019-05-06 12:21发布

问题:

I've a service which starts a notification with startForeground(), I want the notification to launch an activity on click.
The acitivty I want to launch defined as android:launchMode="singleTask" and usually runs before the service starts.
Here is my pending intent creation code :

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

When I click on the notification I get the following warning :

startActivity called from non-Activity context; 
forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent........

I've also tried getting the activity with this instead of getApplicationContext() but got the same warning.
How should I make this right ?

回答1:

Don't use Intent.FLAG_ACTIVITY_NEW_TASK for PendingIntent.getActivity. Better use FLAG_ONE_SHOT.

And try to use Context of Activity instead getApplicationContext().