我有一个发送通知的应用程序,但是当用户离开该应用程序时,如果他没有单击该通知,通知仍然存在。 因此,当用户注销或会话用户为“空”时,通知将被自动删除。
我的代码:
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void enviarNotificacao(){
Intent intent = new Intent(this, BottomNavigation.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.putExtra("totens", listaTotem);
int id = (int) (Math.random()*1000);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("Olá Marujo!!!");
builder.setContentTitle("Capitão Cupom");
builder.setContentText("Um novo tesouro próximo de você");
builder.setSmallIcon(R.drawable.logo);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
builder.setContentIntent(pi);
builder.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(id, builder.build());
Notification n = builder.build();
n.vibrate = new long[]{150, 300, 150, 600};
notificationManager.notify(R.drawable.logo, n);
try {
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(this, som);
toque.play();
}catch (Exception e){
}
Sessao.instance.setSailor(sailor);
}
答案 0 :(得分:1)
NotificantionManager.cancel(id)取消具有该ID的通知。 NoticiationManager.cancelAll()取消此应用程序的所有通知。检测会话何时结束显然是您需要构建的业务逻辑。发生这种情况时,请调用上述两个函数之一。
答案 1 :(得分:1)
在Activity中重写onPause()并将其放在里面:
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
答案 2 :(得分:1)
离开应用程序时调用它
notificationManager.cancel(NOTIFICATION_ID);