AlarmManager and Timer
1. The Alarm Manager holds a CPU wake lock as long as the alarm receiver’s onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast.
2. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.3. If an alarm is delayed (by system sleep, for example, for non _WAKEUP alarm types), a skipped repeat will be delivered as soon as possible. For example, if you have set a recurring alarm for the top of every hour but the phone was asleep from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens, then the next alarm will be sent at 9:00.Sample:Intent intent = new Intent(AlarmActivity.this, AlarmReceiver.class);PendingIntent pi = PendingIntent.getBroadcast(AlarmActivity.this, 0, intent, 0);AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), (10 * 1000), pi);
4. Each timer has one thread on which tasks are executed sequentially.5(1)schedule方法:下一次执行时间相对于 上一次 实际执行完成的时间点 ,因此执行时间会不断延后
(2)scheduleAtFixedRate方法:下一次执行时间相对于上一次开始的 时间点 ,因此执行时间不会延后,存在并发性 6. 手机SleepTimer依然执行
Sample: TimerTask task = new SyncContactsTimerTask(); delay = genDelay();
mTimer.schedule(new BackupContactsTimerTask(), delay, TIMER_TASK_PERIOD);
private final class BackupContactsTimerTask extends TimerTask { public void run() { if (DBG) { LogUtil.i(ContactBackupRestore.TAG, "BackupContactsTimerTask run() begin"); } if (ContactBackupRestore.getAutoSyncPref(ContactsService.this) != 0) { ContactBackupRestore.setIsAutoBackingUp(ContactsService.this, 1); backupContacts(); } } }