如何使用 BroadcastReceiver 处理 Notification Touch 事件启动 Activity

How to handle Notification Touch event launch Activity using BroadcastReceiver

我用过广播接收器警报管理器。添加了特定日期和时间的通知。 通知 显示正常。但是当用户触摸通知n时,我想启动我的应用程序

    Notification.Builder notification= new Notification.Builder(this);
    notification.setContentTitle("MY Title");
    notification.setContentText("Today you have scheduled for...");
    notification.setSmallIcon(R.drawable.ic_app_launcher);
    notification.setAutoCancel(true);
    notification.build();    

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    long futureInMillis =  dateSpecified.getTime(); //Some future date like 20 feb 2015 
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);

NotificationPublisher class -BroadcastReciver

public class NotificationPublisher extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);

   }
}

我提到了这个 link。 我希望你明白我想说的话。

请任何人帮助我。非常感谢。

But when the user is touching the notification i want to launch myApplication.

因为 NotificationPublisher BroadcastReceiver 在点击通知时触发,所以从 Receiver 的 onReceive 方法启动应用程序:

    public void onReceive(Context context, Intent intent) {
          // start application here
    NotificationManager notificationManager = (NotificationManager)
                         context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);

    Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent intentn = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intentn);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(id, notification); 
  }