Up to parent activity - on Android

后端 未结 7 1554
有刺的猬
有刺的猬 2021-01-17 13:06

After receiving a notification in my app, clicking on it opens activity B. Activity B has a parent activity A. Here is the manifest:



        
7条回答
  •  悲&欢浪女
    2021-01-17 13:33

    You need to set up the PendingIntent which is used to build Notification, to start a fresh task, and provide the PendingIntent with a back stack to achieve the application's normal Up behavior.

    Intent resultIntent = new Intent(this, SecondActivity.class);
    
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // All the parents of SecondActivity will be added to task stack.
    stackBuilder.addParentStack(SecondActivity.class);
    // Add a SecondActivity intent to the task stack.
    stackBuilder.addNextIntent(resultIntent);
    
    // Obtain a PendingIntent for launching the task constructed by this builder.
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(REQUEST_CODE, PendingIntent.FLAG_UPDATE_CURRENT);
    
    NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new Notification.Builder(this)
        .setContentTitle("My Notification")
        .setContentText("Notification content")
        .setSmallIcon(android.R.drawable.ic_menu_view)
        .setContentIntent(pendingIntent)
        .build();
    
    manager.notify(NOTIFICATION_ID, notification);
    

    Please read the Android official documentation on Preserving Navigation when Starting an Activity. It recommends the above approach.

提交回复
热议问题