我想在一天内显示随机通知,所以我设置了一个警报,通过我的共享首选项将触发时间作为一个值,默认值为 10。代码如下:
Calendar calendar;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
int nextAlarm = prefs.getInt("nextAlarm", 10);
Intent i = new Intent(this, NotificationBarAlarm.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, nextAlarm);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
long alarmmills = calendar.getTimeInMillis();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarmmills, pi);
警报正在发送未决意图以激活我的通知过程。每当调用通知时,我都会计算当前时间毫秒加上随机的毫秒数,然后将它们转换为小时并将时间存储在我的共享首选项中,以便将其用于我的下一个警报。最后,我向我的警报服务发送了一个意图,以便对其进行更新。代码如下:
NotificationManager notifyManager;
@Override
public void onReceive(Context context, Intent intent) {
Time time = new Time();
long currenttimeMilliseconds = System.currentTimeMillis();
time.set(currenttimeMilliseconds);
int t = time.hour;
//Random time
Random rand=new Random();
int min = 1, max = 2;
int randomNum = rand.nextInt(max - min + 1) + min;
long randomMilli=randomNum *60*60*1000;
long updatedTime= currenttimeMilliseconds + 10800000 +randomMilli;
Time nextalarmmill = new Time();
nextalarmmill.set(updatedTime);
int nextalarm = nextalarmmill.hour;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("nextAlarm", nextalarm);
editor.commit();
if (t >= 10 && t <= 22) {
notifyManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context,
AlarmReceiverActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"A new notification just popped in!",
System.currentTimeMillis());
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notif.sound = alarmSound;
notif.setLatestEventInfo(context, "Notification",
"A new notification", contentIntent);
notifyManager.notify(1, notif);
}
Intent serviceIntent = new Intent(context, AlarmService.class);
context.startService(serviceIntent);
}
它工作正常,直到天变。例如,在 27/07 下午 21:00 我打电话通知下一个警报设置为激活(在 4 或 5 小时后随机)让我们说在上午 01:00。警报不明白 01:00 不是指今天 (27/07) 而是指下一天 (28/7)。结果,它立即触发了我的通知接收器,这又再次激活了我的警报服务,从而创建了一个循环。
我如何设置闹钟以便了解这一天的变化?