通知管理器不在android中的倒计时器类中工作

时间:2012-04-10 06:04:13

标签: java android notifications

我正在使用倒数计时器类,并且在该类的onfinish()状态下,我正在创建通知。这是Onfinish方法的代码:

public void onFinish() {
            notificate();
            Log.i("Aler Resume", "Finished");
            remtime.setText("0 : 00 : 00");
            textCondition.setText(getString(R.string.BuddyAlertExpired));
              }

在我写的notificate()方法中:

private void notificate() {
        NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  

        Notification note = new Notification(R.drawable.ic_launcher, "New E-mail", System.currentTimeMillis());  

         PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, AlertResume.class), 0); 
         note.setLatestEventInfo(this, "Buddy Alert", getString(R.string.BuddyAlertExpired), intent); 
         note.defaults= Notification.DEFAULT_VIBRATE;
         note.defaults=Notification.DEFAULT_SOUND;
         notifManager.notify(NOTIF_ID, note); 


    }

当我保持应用程序打开时,它工作正常。但是当我从应用程序返回时,调用onfinish方法并且我可以正确地看到日志但是notofication方法不起作用并且不显示任何通知。有什么错吗?

1 个答案:

答案 0 :(得分:0)

当你离开应用程序时,可能会发生Android认为你的进程运行CountDown Timer作为垃圾邮件或额外而非意图。并完成它...(就像它认为你忘了关闭让我关闭)

所以最好使用AlarmManager来完成上述内容,例如设置PendingIntent - Notification,在你开始倒计时器的时候,也可以通过使用ALARM MANAGER的意图来设置通知。

        nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.icon, "Test", System.currentTimeMillis());

        Intent intentTL = new Intent(context, MainActivity.class);
        notification.setLatestEventInfo(context, "Test", "Do something!",
                PendingIntent.getActivity(context, 0, intentTL,
                PendingIntent.FLAG_CANCEL_CURRENT));
        notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
        nm.notify(1, notification);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);