David_D
David_D

Reputation: 1402

Notification for several seconds in notifications bar?

how can i create a notification in the notifications bar that disappear after 5 seconds? For example; this is the notification code:

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
        .setContentTitle("Notification")
        .setContentText("This is a notification that didsappears in 5 seconds")
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .addAction(R.drawable.icon)


NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


notificationManager.notify(0, noti);

Starting from this code how can i create my notification that disappear after 5 seconds?

Upvotes: 3

Views: 1718

Answers (2)

user1744056
user1744056

Reputation:

You can simply cancel your notification after 5 seconds.For this you can use either Timer or Handler.Here is Handler solution:

 Handler handler = new Handler();
 long delayInMilliseconds = 5000;
 handler.postDelayed(new Runnable() {

    public void run() {
        notificationManager.cancel(YourNotificationId);
    }}, delayInMilliseconds);

if you want to use Timer instead of Handler. Then you can try:

Timer timer = new Timer();
  timer.schedule(new TimerTask()
{
   public void run()
   {
     notificationManager.cancel(YourNotificationId);
   }},delayInMilliseconds);
}

Upvotes: 5

Semyon Danilov
Semyon Danilov

Reputation: 1773

You can use method cancel(int id) or cancelAll() to dismiss your notifications. Start a timer for 5 seconds and when it ends call cancell(); http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

Upvotes: 1

Related Questions