简体   繁体   中英

Android onCreate() not called with Notification

I have met with interesting intent workflow handling. I create a notification like this:

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.abc_textfield_search_default_holo_dark).setContentTitle("Мероприятие изменилось")
        .setContentText(eventToShow.valueAt(i).name + " " + eventToShow.valueAt(i).date).setAutoCancel(true);
    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra(MainActivity.NOTIFICATION_EVENT_DISPLAY, eventToShow.valueAt(i).id);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(eventToShow.valueAt(i).id, mBuilder.build());

When notificataion is arrived to user, i expect that when he clicks on it MainActivity.class will handle this intent. I process information about intent inside MainActivity.onCreate() .

Everything goes ok if i click on notification outside my app. Activity correctly processing this intent and shows what i expected.

But when i click on notification inside my app there is no new instanse of my MainActivity.class And onCreate() is not firing. I thought that it will be created new Instance of MainActivity.class

Can you explain me is this a default behavior and how should i handle this situation?

After testing my app i find next.

a) MainActivity -> get notification -> Close app -> Open app(MainActivity) -> press notification -> Notification opening new instance of MainActivity as expected.

b) MainActivity -> get notification -> press notification -> nothing is happened

So i was researching about one day to fix that bug and here what i has found. I am certainly sure that Android task system can give you headache. It seem's that if Android decides that you are calling your intent from non-Activity context it can be replased with new Intent.

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

And this intent will replace your original intent and you will not catch any data that you insert to it.

You can do next to prevent this situation. In your activity you should Override next method:

@Override
public void onNewIntent(Intent intent) {
int eventId = intent.getIntExtra(MainActivity.NOTIFICATION_EVENT_DISPLAY, -1); 
}

And now you can handle this data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM