在5分钟后使通知消失

4

在一段时间后,是否有可能让通知自动消失?


可能是清除几秒钟后的通知的重复问题。 - mike47
5个回答

4
您可以使用AlarmManager。我认为这比使用Android服务更合适且更易于实现。
使用AlarmManager,您不需要担心运行某些内容直到时间结束。 Android会为您完成此操作,并在发生时发送广播。您的应用程序必须有一个接收器以获取正确的意图。 看看这些示例:

2

1

是的,这很容易。 在你收到通知的地方添加一个处理程序,如果用户没有阅读通知,则删除通知。

@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);
}

1

是的,你可以创建一个在后台运行并在五分钟后超时并删除通知的服务。是否应该这样做还有待商榷。通知应该存在于那里以通知用户...用户应该能够自己解除通知。

来自d.android.com:

服务是一种应用程序组件,可以在后台执行长时间运行的操作,并且不提供用户界面。


-1

你也可以使用经典的Java Runnable来创建一个简单的小线程。

Handler h = new Handler();
    long delayInMilliseconds = 5000;
    h.postDelayed(new Runnable() {
        public void run() {
            mNotificationManager.cancel(id);
        }
    }, delayInMilliseconds);

还可以看这里:

几秒钟后清除通知


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接