简体   繁体   中英

Notification Auto Cancel at a Particular Time

I am a beginner for Java Coding and is currently coding an Android Project. Right now, I am facing an issue. I want my application to auto remove the notification at a particular time.

I've managed to dismiss the notification after user click on the notification . However, at the same time, I also want the notification to auto disappear after a specific time if the user did not react to the notification .

Please advise me on how should I do it. If possible, please provide me some examples.

You can start a timer for required seconds as soon you call the method to show notification and inside onFinish() of the timer you can add something like this :

NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();

You can set a timer or something like an alarm and when your criteria is fulfilled, cancel it using :

 //clear all pending notifications
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) context.getSystemService(ns);
        nMgr.cancelAll();

you can use Timer for required timing and for remove Notification you can use cancel()

nMgr.cancel(<notification-id>); // here you have to pass your notification id.

If you want to remove all notifications just use

nMgr.cancelAll();

If you want to remove notification after 2 seconds you can use :

    Timer timer=new Timer();
    TimerTask task=new TimerTask() {

        @Override
        public void run() {
            nMgr.cancel(notification-id);
        }
    };

    timer.schedule(task, 2000);

i suggest use handler method to remove the notification from the notification bar. You can specify the time lenght in miliseconds at handler. this will recalled once only after the entered time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM