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

前端 未结 8 1234
星月不相逢
星月不相逢 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

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

提交回复
热议问题