在通知点击时启动同一活动,并设置标志来检测是否需要创建新的实例。代码示例:
// on create boolean isFromNotification = false; Bundle extras = getIntent().getExtras(); if (extras != null) { isFromNotification = extras.getBoolean("FROM_NOTIFICATION", false); }
if (isFromNotification) { // do something when starting from notification } else { // do something else when starting normally }
// on notification click Intent intent = new Intent(this, MyActivity.class); intent.putExtra("FROM_NOTIFICATION", true); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Notification Title") .setContentText("Notification Text") .setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, builder.build());