在我的应用程序中,我使用AlarmManager
类来设置闹钟。为了在手机重启后触发警报,我使用了BroadcastReceiver
. 一切正常,我的警报会定期触发。现在问题出现在这种情况下:
假设我现在的时间是2:30 pm并且我将闹钟设置在2:35 pm。之后,我关掉了手机。当我打开手机一个小时后,没有弹出闹钟作为设置闹钟的时间。发生这种情况是因为当前时间超过了我设置闹钟的时间。要解决这个问题我应该怎么做。我已经在AlarmManager
课堂上发布了设置警报的代码。请帮我解决这个问题
public class AlarmReceiver extends BroadcastReceiver {
@SuppressWarnings("static-access")
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent myIntent = new Intent(context, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, i, myIntent, i);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MILLISECOND, (int) Utilities.diff(NoteManager.getSingletonObject().getAlarmTime(i)));
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
}
public static long diff(Date date) {
long difference = 0;
try {
// set current time
Calendar c = Calendar.getInstance();
difference = date.getTime() - c.getTimeInMillis();
if (difference < 0) {
// if difference is -1 - means alarm time is of previous time then current
// then firstly change it to +positive and subtract form 86400000 to get exact new time to play alarm
// 86400000-Total no of milliseconds of 24hr Day
difference = difference * -1;
difference = 86400000 - difference;
}
}
catch (Exception e) {
e.printStackTrace();
}
return difference;
}
在清单文件中
<receiver android:name=".AlarmReciever">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />