【发布时间】:2013-03-08 01:25:00
【问题描述】:
我正在尝试实现一个警报,它会在每天的同一时间显示通知。
这是我在活动中调用的函数:
private void restartNotify() {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Intent for our BroadcastReceiver
Intent intent = new Intent(this, AlarmReceiver.class);
// PendingIntent for AlarmManager
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT );
// In case we have already set up AlarmManager, we cancel.
am.cancel(pendingIntent);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, pendingIntent);
}
这是我的广播接收器类
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon_notif, context.getString(R.string.NotificationLaunchMssg), System.currentTimeMillis());
// This is intent we want to launch when user clicks on the notification.
Intent intentTL = new Intent(context, MyClass.class);
notification.setLatestEventInfo(context, context.getString(R.string.NotificationTitle), context.getString(R.string.NotificationBody),
PendingIntent.getActivity(context, 0, intentTL, PendingIntent.FLAG_CANCEL_CURRENT));
nm.notify(1, notification);
//Here we set next notification, in day interval
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);
}
}
正如您在这段代码中看到的那样,我使用的是测试值(+10000 毫秒),因为我只是想在我的应用程序启动 10 秒后触发警报。但它不起作用,什么都没有显示。 不知道是闹钟有问题,还是通知,什么都没有发生。
你知道为什么吗?
感谢您的帮助
编辑:在 AlarmReceiver 方法中添加一些测试代码后,事实证明该代码从未运行。所以我可能没有正确调用它,有什么问题?
【问题讨论】:
-
您将闹钟设置在 12:00,而不是应用启动后的 10 秒。尝试添加一些日志信息以查看是否接收到广播。
-
你说得对,我的问题中有脏代码,我现在用 System.currentTimeMillis() 进行了编辑
-
这样您就可以在一天中的这个时间点发出警报。到注册时,时间已经过去了。
-
好吧,我不明白的是我应该在哪里设置未来的触发时间:在我的活动中重新启动通知?或者在我的课堂上 AlarmReceiver ?现在我在我的活动中设置当前时间,在我的班级 AlarmReceiver 中设置当前时间 + 10 秒
-
在你设置的第一个警报何时触发的活动中(你需要这里的+10秒)。在您设置的接收器中,当下一个触发时,您再次需要 +10 秒。
标签: android notifications alarm