通过删除通知关闭应用程序


@RequiresApi(api = Build.VERSION_CODES.M)
public void showNotification(int playPauseBtn) {
Intent intent = new Intent(this, ExoActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, prevIntent,
PendingIntent.FLAG_MUTABLE);
Intent playIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, playIntent,
PendingIntent.FLAG_MUTABLE);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, nextIntent,
PendingIntent.FLAG_MUTABLE);
Bitmap picture = BitmapFactory.decodeResource(getResources(), HelperClass.getlist().get(position).getImg());
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(HelperClass.getlist().get(position).getImg())    //get thumbnail will have small icon pic
.setLargeIcon(picture)
.setContentTitle(HelperClass.getlist().get(position).getName())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPendingIntent)
.addAction(R.drawable.ic_baseline_play_arrow_24, "Play", playPendingIntent)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPendingIntent)
//.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
//.setMediaSession(mediaSession.getSessionToken()))
.setPriority(Notification.PRIORITY_HIGH)
.setC`your text`ontentIntent(contentIntent)
.setOnlyAlertOnce(true).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}

这段代码在调用'showNotification()'函数的地方创建通知,但是如果我想通过删除通知来关闭应用程序怎么办?

使用setDeleteIntent方法-当通知被删除时,您可以发送一些广播到您所有的上下文"对象(如Activity,Service)

注意,还有setOngoing方法,它将粘贴您的通知,用户将无法"手动"删除它。然后你可以提供"杀戮";此通知的action按钮,其行为可能与为setDeleteIntent创建的完全相同。在这种情况下,不要忘记删除通知当用户离开/退出你的应用程序,当"kill"按下的动作或任何其他"通常"的动作;

最新更新