在Android中,我使用AlarmManager设置每天执行一次的重复任务。用户可以选择此警报的时间。例如,当他选择9点钟时,每天9点执行一个给定的任务,即启动未决意图,将通知发送到通知栏。
我的应用的用户说当时他们的设备已关闭,根本没有通知。当警报响起时设备关闭时,再次启动后警报不会重复吗?
如果这是正常行为,怎么可能被规避呢?我应该在触发通知的IntentService中编写共享首选项(例如“last_execution_time”)吗?在启动时,我可以检查最后一次执行是否超过24小时,如果是,重复一次?
答案 0 :(得分:0)
使用动作android.intent.action.BOOT_COMPLETED
注册广播接收器以获取意图,这将启动与您使用AlarmManager安排的相同任务(以前确保它不会在适当的时候被AlarmManager触发)。
编辑: 为了保持跟踪尝试......(它只是一个提示 - 自己安全地处理9个确切的时间;)
public class KeepTrackReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences p = context.getSharedPreferences(
TrackedAlarmService.FILE_ALARM_TRACK, Context.MODE_PRIVATE);
long lastAlarm = p.getLong(TrackedAlarmService.KEY_LAST_ALARM_MILLIS, -1L);
if(lastAlarm == -1L || lastAlarm < TrackedAlarmService.getClosest9AM(false)) {
context.startService(TrackedAlarmService.createIntent(context));
}
}
}
public class TrackedAlarmService extends IntentService {
public static final String FILE_ALARM_TRACK = "alarmTrack";
public static final String KEY_LAST_ALARM_MILLIS = "lastAlarmMillis";
public static void schedule(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0,
createIntent(context), PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, getClosest9AM(true),
AlarmManager.INTERVAL_DAY, pi);
}
public static long getClosest9AM(boolean futurePastFlag) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
if(futurePastFlag) {
if(c.get(Calendar.HOUR_OF_DAY) > 9) {
c.roll(Calendar.DATE, true);
}
}
else {
if(c.get(Calendar.HOUR_OF_DAY) < 9) {
c.roll(Calendar.DATE, false);
}
}
c.set(Calendar.HOUR_OF_DAY, 9);
c.set(Calendar.MINUTE, 0);
return c.getTimeInMillis();
}
public static Intent createIntent(Context context) {
return new Intent(context, TrackedAlarmService.class);
}
public TrackedAlarmService() {
super("TrackedAlarmService");
}
@Override
protected void onHandleIntent(Intent intent) {
//save last alarm time
getSharedPreferences(FILE_ALARM_TRACK, MODE_PRIVATE)
.edit()
.putLong(KEY_LAST_ALARM_MILLIS, System.currentTimeMillis())
.commit();
// Do your repeating job....
}
}