Notification bar click to close app

2019-04-17 06:07发布

问题:

How can I close app when user clicks on text in notification bar without displaying any window?

回答1:

Use the following code and register broadcast receiver in your activity :

NotificationManager mNotificationManager = (NotificationManager)_context.getSystemService(Context.NOTIFICATION_SERVICE);   

Notification notification = new Notification(R.drawable.icon,"",System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;


Context context = _context.getApplicationContext();


/** Set the intent extras to be passed to calling activity*/
Intent notificationIntent = new Intent("action_close_app");



/** Create a pending intent, requires to generate a notification */

PendingIntent contentIntent = PendingIntent.getBroadcase(
  _context.getApplicationContext(), requestCode,
  notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


/** Set notification with required fields */

notification.setLatestEventInfo(context, "", "", contentIntent);



/** notify manager to generate notification on status bar*/

mNotificationManager.notify(NOTIFICATION_ID, notification)


回答2:

create the notification use getBroadcast

Intent intent = new Intent("action_close_app");

PendingIntent closeIntent = PendingIntent.getBroadcast(context, requestCode, intent, flags)

when you click the notification, will send a broadcast with the action action_close_app, you need register a broadcast receiver to process action_close_app receive, just close your app.