如何在通知栏中创建一个在5秒后消失的通知? 例如;这是通知代码:
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);
从这段代码开始,如何创建5秒后消失的通知?
答案 0 :(得分:5)
您可以在5秒后取消通知。为此,您可以使用Timer
或Handler
。这是Handler
解决方案:
Handler handler = new Handler();
long delayInMilliseconds = 5000;
handler.postDelayed(new Runnable() {
public void run() {
notificationManager.cancel(YourNotificationId);
}}, delayInMilliseconds);
如果您想使用Timer而不是Handler
。然后你可以尝试:
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
notificationManager.cancel(YourNotificationId);
}},delayInMilliseconds);
}
答案 1 :(得分:1)
您可以使用方法cancel(int id)
或cancelAll()
来解除您的通知。
启动计时器5秒钟,当它结束时调用cancell();
http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)