'startactivity called from non-activity contex

2019-05-06 12:40发布

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条回答
别忘想泡老子
2楼-- · 2019-05-06 13:09

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().

查看更多
登录 后发表回答