Android 通知未被销毁
Android notifications not being destroyed
我在销毁 android 中的通知时遇到问题。
我的应用程序在特定时间生成一些通知,我希望在一段时间(60 秒)后自动删除这些通知。
通知由 BroadcastReceiver
创建,它捕获由 alarmManager
创建的广播,然后从广播的 intent
中提取信息并创建通知。
有时这行得通,有时行不通。
我认为这是因为 android 终止了一些进程或类似的东西,但我在网上找不到任何东西。
这是我的代码片段:
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId,notification);
Log.d("AlarmReveiver","id della notifica: " + String.valueOf(notificationId));
//cancella la notifica quando l'orario è passato
Handler handler = new Handler();
long delay = 60*1000;
final int lullo = notificationId;
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("Handler","id della notifica: " + String.valueOf(lullo));
notificationManager.cancel(lullo);
}
},delay);
notificationId++;
注意notificationId
是一个static int
;我想我可以使用一个静态变量来获得到目前为止创建的通知数量,以避免通知 ID 混乱,但我看到这个计数器在一段时间后被重新初始化为 0。
有没有人知道更好的方法(每次都有效的方法,哈哈)?
提前致谢
您不能假设应用程序将保持常驻状态。您绝对不能指望应用程序保留足够长的时间让处理程序处理您的消息。这意味着在对 BroadcastReceiver 的任意两次调用之间,它可能会丢失所有静态信息。而不是处理程序,而是使用 AlarmManager 警报并将 if 取消放入意图中。
顺便说一句,我今天碰巧发布了我的计时器 class,它简化了警报的处理。查看 http://gabesechansoftware.com/timers-in-android/
我在销毁 android 中的通知时遇到问题。
我的应用程序在特定时间生成一些通知,我希望在一段时间(60 秒)后自动删除这些通知。
通知由 BroadcastReceiver
创建,它捕获由 alarmManager
创建的广播,然后从广播的 intent
中提取信息并创建通知。
有时这行得通,有时行不通。
我认为这是因为 android 终止了一些进程或类似的东西,但我在网上找不到任何东西。
这是我的代码片段:
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId,notification);
Log.d("AlarmReveiver","id della notifica: " + String.valueOf(notificationId));
//cancella la notifica quando l'orario è passato
Handler handler = new Handler();
long delay = 60*1000;
final int lullo = notificationId;
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("Handler","id della notifica: " + String.valueOf(lullo));
notificationManager.cancel(lullo);
}
},delay);
notificationId++;
注意notificationId
是一个static int
;我想我可以使用一个静态变量来获得到目前为止创建的通知数量,以避免通知 ID 混乱,但我看到这个计数器在一段时间后被重新初始化为 0。
有没有人知道更好的方法(每次都有效的方法,哈哈)?
提前致谢
您不能假设应用程序将保持常驻状态。您绝对不能指望应用程序保留足够长的时间让处理程序处理您的消息。这意味着在对 BroadcastReceiver 的任意两次调用之间,它可能会丢失所有静态信息。而不是处理程序,而是使用 AlarmManager 警报并将 if 取消放入意图中。
顺便说一句,我今天碰巧发布了我的计时器 class,它简化了警报的处理。查看 http://gabesechansoftware.com/timers-in-android/