单击android Notification后退出应用程序

时间:2017-03-28 01:08:32

标签: 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);
}

我该怎么做??

2 个答案:

答案 0 :(得分:2)

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

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

然后在你的onCreate:

    private BroadcastReceiver mReceiver;

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

然后接收您的行动并在onCreate或onResume上注册:

      IntentFilter filter = new IntentFilter();
      filter.addAction("close_app");
      registerReceiver(mReceiver, filter);

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

答案 1 :(得分:0)

您的意思是关闭申请或活动吗?

通常,如果长时间不使用活动,活动将被回收。

如果要杀死该应用程序,可以使用:

Process.killProcess(Process.myPid())