单击 android 通知后退出应用程序

Das*_*all 1 android android-notifications

我已经实现了一种方法,当我的应用程序在后台运行时,通知将显示在通知栏上。现在我想在单击该通知时关闭应用程序:

Intent intent = new Intent(this, Main.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 
                            (int) System.currentTimeMillis(), intent, 0);
if (Build.VERSION.SDK_INT < 16) {
    Notification n  = new Notification.Builder(this)
            .setContentTitle("Flashlight")
            .setContentText("turn off")
            .setSmallIcon(R.mipmap.light_on)
            .setContentIntent(pIntent)
            .setAutoCancel(true).getNotification();
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, n);
} else {
    Notification n  = new Notification.Builder(this)
            .setContentTitle("Flashlight")
            .setContentText("turn off")
            .setSmallIcon(R.mipmap.light_on)
            .setContentIntent(pIntent)
            .setAutoCancel(true).build();
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, n);
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 !?

S.R*_*S.R 5

如果您需要退出应用程序,您可以为您的意图设置一个操作,然后创建一个广播接收器并在 onReceive 方法中完成您的应用程序,然后使用 IntentFilter 接收您的操作,并使用操作过滤器注册您的接收器。这是一个例子:

Intent intent = new Intent("close_app");
PendingIntent pIntent = PendingIntent.getBroadcast(this, (int) 
                System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
.
.
.// build your notification
Run Code Online (Sandbox Code Playgroud)

然后在你的 onCreate 中:

    private BroadcastReceiver mReceiver;

    mReceiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
         Log.d("TAG" ,"onReceive ");
         finish();
       }
     };
Run Code Online (Sandbox Code Playgroud)

然后接收您的操作并在 onCreate 或 onResume 中注册:

      IntentFilter filter = new IntentFilter();
      filter.addAction("close_app");
      registerReceiver(mReceiver, filter);
Run Code Online (Sandbox Code Playgroud)

并且不要忘记取消注册您的接收器