0

我遇到了在Android中销毁通知的问题。 我的应用程序在特定的时间生成一些通知,我想在一段时间后(60秒)自动删除。 通知由BroadcastReceiver创建,它捕获由alarmManager创建的广播,然后从广播的intent中提取信息并创建通知。 有时候这种方式有效,有时候不行。
我认为这是因为android终止某个过程或类似的东西,但我无法在网上找到任何东西。 这里是我的代码片段: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++; 

注意notificationIdstatic int;我猜想我可以使用一个静态变量来创建迄今为止创建的通知数量,以避免与通知ID混淆,但是我看到这个计数器在一段时间后被重新初始化为0。

有没有人知道一个更好的方式(一种方法,每次工作大声笑)做到这一点?

在此先感谢

回答

2

您不能假设应用程序将保持常驻状态。您绝对不能指望应用程序保持足够长的时间,以便处理程序处理您的消息。这意味着在对BroadcastReceiver的任何两次调用之间,它可能会丢失所有静态信息。相反,对于处理程序,请使用AlarmManager警报,并将if取消为意图。另外,我恰巧今天发布了我的Timer类,它简化了报警处理。退房http://gabesechansoftware.com/timers-in-android/

+0

这就是我所怀疑的。非常感谢,我会看看你的班级并修复一切。 谢谢! – magicleon