【发布时间】:2016-10-27 18:44:15
【问题描述】:
我在尝试设置每日通知时遇到问题。
我使用AlarmManager 设置了每天下午 6:00 的闹钟
Intent myIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY) >= 18) {
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.HOUR_OF_DAY, 18);
alarmManager.cancel(pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 24*60*60*1000,
pendingIntent);
但我不知道为什么第一个警报会在 18:00 准确触发,但下一个警报会在随机时间触发。有时是 19:30,有时是 20:06。我只是不明白我在这里做错了什么。
我尝试了INTERVAL_DAY 或24*60*60*1000 - 没有任何效果。
但它工作正常,间隔为 1 分钟、5 分钟、10 分钟、1 小时等。
报警接收器:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
System.out.println("alarm");
}
}
我的报警服务:
public class MyAlarmService extends Service {
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"Test notification", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "Test", "Test a notification", pendingNotificationIntent);
mManager.notify(0, notification);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
【问题讨论】:
-
你在什么上运行代码?它是 Android 4.4 设备还是模拟器?或者是别的什么?另外,您使用的
PendingIntent是什么? -
我添加了我的 pendintIntent 代码,它只是一个简单的接收器,用于在触发警报时显示通知
标签: android notifications alarmmanager