Intent - if activity is running, bring it to front, else start a new one (from notification)

前端 未结 8 1201
星月不相逢
星月不相逢 2020-11-27 13:57

My app has notifications, which - obviously - without any flags, start a new activity every time so I get multiple same activities running on top of each other, which is jus

相关标签:
8条回答
  • 2020-11-27 14:32

    This is old thread, but for all those who is still seeking for answer, here is my solution. It is purely in code, without manifest settings:

    private static PendingIntent prepareIntent(Context context) {
      Intent intent = new Intent(context, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);      
      return PendingIntent.getActivity(context, NON_ZERO_REQUEST_CODE, intent, 
        PendingIntent.FLAG_UPDATE_CURRENT);
    }
    

    Here FLAG_ACTIVITY_SINGLE_TOP opens existing activity if it is at the top of task stack. If it is not at the top, but inside stack, FLAG_ACTIVITY_CLEAR_TOP will remove all activities on top of target activity and show it. If activity is not in the task stack, new one will be created. A crucially important point to mention - second parameter of PendingIntent.getActivity(), i.e. requestCode should have non-zero value (I even called it NON_ZERO_REQUEST_CODE in my snippet), otherwise those intent flags will not work. I have no idea why it is as it is. Flag FLAG_ACTIVITY_SINGLE_TOP is interchangeable with android:launchMode="singleTop" in activity tag in manifest.

    0 讨论(0)
  • 2020-11-27 14:32

    I tried this, and it worked even though the IDE was complaining about the code

    Intent notificationIntent = new Intent(THIS_CONTEXT, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        PendingIntent intent = PendingIntent.getActivity(THIS_CONTEXT, 0, notificationIntent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(THIS_CONTEXT)
                .setSmallIcon(R.drawable.cast_ic_notification_0)
                .setContentTitle("Title")
                .setContentText("Content")
                .setContentIntent(intent)
                .setPriority(PRIORITY_HIGH) //private static final PRIORITY_HIGH = 5;
                .setAutoCancel(true)
                /*.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)*/;
        NotificationManager mNotificationManager = (NotificationManager) THIS_CONTEXT.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    
    0 讨论(0)
提交回复
热议问题