Android 使通知在5分钟后消失
有没有可能使通知在一段时间后自动消失?是的,您可以创建一个在后台运行的服务,该服务将在五分钟后超时并删除通知。你是否“应该”真的这样做还有待讨论。应该有一个通知通知用户。。。而且用户应该能够自己解除它 服务是可以执行长时间运行的应用程序组件 在后台操作,不提供用户界面 您可以使用。我认为这比安卓服务更合适,也更容易实现 使用Android 使通知在5分钟后消失,android,Android,有没有可能使通知在一段时间后自动消失?是的,您可以创建一个在后台运行的服务,该服务将在五分钟后超时并删除通知。你是否“应该”真的这样做还有待讨论。应该有一个通知通知用户。。。而且用户应该能够自己解除它 服务是可以执行长时间运行的应用程序组件 在后台操作,不提供用户界面 您可以使用。我认为这比安卓服务更合适,也更容易实现 使用AlarmManager您不必担心在时间结束之前让某些东西运行。Android会为你做这件事,当事情发生时,会发送brodcast。您的应用程序必须有一个接收器才能获得正确
AlarmManager
您不必担心在时间结束之前让某些东西运行。Android会为你做这件事,当事情发生时,会发送brodcast。您的应用程序必须有一个接收器才能获得正确的目的。
private void removeNotification(int id) {
Handler handler = new Handler();
long delayInMilliseconds = 20000;
handler.postDelayed(new Runnable() {
public void run() {
notificationManager.cancel(id);
}
}, delayInMilliseconds);
}
看看这些例子:
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
mNotificationManager.cancel(id);
}
}, delayInMilliseconds);
请看这里:
是的,这很容易。
若用户未读取通知,则在获取通知的位置添加一个处理程序,然后删除通知
@Override
public void onMessageReceived(RemoteMessage message) {
sendNotification(message.getData().toString);
}
添加通知代码
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("TEST NOTIFICATION")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int id = 0;
notificationManager.notify(id, notificationBuilder.build());
removeNotification(id);
}
取消通知代码。
private void removeNotification(int id) {
Handler handler = new Handler();
long delayInMilliseconds = 20000;
handler.postDelayed(new Runnable() {
public void run() {
notificationManager.cancel(id);
}
}, delayInMilliseconds);
}
现在有一个名为
.setTimeoutAfter(长持续时间)
可能存在的副本