通过添加FLAG_ACTIVITY_CLEAR_TOP标志和设置Intent的数据,可以防止应用在接收到通知并单击通知时重新启动。例如:
Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("fromNotification", true); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true);
请确保MainActivity能够处理Intent,并使用getIntent().getExtras()来检查是否从通知启动。
参考资料:https://stackoverflow.com/questions/7195934/how-to-make-notification-click-to-cause-an-activity-to-be-brought-to-front/7196305#7196305