使用 action 为意图注册广播接收器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....
}
}