Resume application and stack from notification

后端 未结 8 1635
一向
一向 2020-11-22 16:04

I want to resume my app from a status bar notification in the exact same manner as when the user taps its icon in the launcher.

That is: I want the stack to be in th

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 16:52

    For situations where you don't want / can't hard code the launcher activity this solution works

    Intent i = getPackageManager()
        .getLaunchIntentForPackage(getPackageName())
        .setPackage(null)
        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
    
    return new NotificationCompat.Builder(context)
            ...
            .setContentIntent(pendingIntent)
            .build();
    

    The setPackage(null) part was key in my case since without it the app did not resume to previous task. I compared my intent with the intent from the Android launcher and noticed that pkg was not set there so that's how I came up with removing package name from the intent.

    My particular situation was that the notification was created in a library so there I could not know what the launcher activity would be.

提交回复
热议问题