AlarmManager
这个类提供访问系统闹钟的服务。它允许你的可以计划你自己的程序在未来的某个时刻可以运行起来。当一个闹钟响了,system就会将为它注册的Intent发送出去,如果程序没有启动,则会自动将其启动。在device休眠的时候注册的alarms将会被保留(alarm同时也可以唤醒设备),但是如果他被关掉,或者重新启动,那就会没了。
Alarm Manager 持有一个CPU 唤醒 锁和receiver的onReceiver()函数被执行的时间一样长。这样就能保证你的手机不会睡眠,除非你结束处理BroadCast。一旦onReceive()函数返回,Alarm Manager 就会释放这个唤醒锁。这就意味着你的设备就会随着OnReceive()函数执行的完成,再次进入睡眠。如果你的alarm receiver调用了 Context.startService(),有可能在你调用的service启动之前,你的手机就再次休眠了。为了解决这点,你的BroadcastReceiver和Service需要实现一个separate wake lock prolicy 来却定在service跑起来之前你的手机还是运行的。
注意点:Alarm Manager 是为了解决你想让你的代码,在特定时间那时程序不在运行的点->运行。对于正常的时间操作,Handler更加高效。
注意点:从API19(KITKAT)alarm 的投递将会变得不准确:OS将会转换alarms来达到最低的唤醒和电池电量的使。有新的API来保证严格的投递保证;setWindow(int, long, long, PendingIntent)和setExact(int, long, PendingIntent)。app的targetSdkVersion在API19之前的还是会准确地投送到。
你并不需要实例化这个类。通过Context.getSystemService(Context.ALARM_SERVICE)获取到。
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ads.class);
intent.putExtra("da", "alarm");
pi = PendingIntent.getBroadcast(this, 0, intent, 0);
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.SECOND, 5);
//time since boot, including sleep
long firsttime = SystemClock.elapsedRealtime();
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firsttime, 1000 * 5, pi);
PowerManager :this class gives you control of the power state of the device.
调用这个api将会被严重影响设备电量。没有需求不要去调用它,用的越少越好,越早释放越好
如果你有一个partial wake lock ,cpu会一直跑,不管显示任何超时或屏幕的状态,甚至是用户按了电源键。其他的wake lock cpu会一直跑,但是用户通过单击电源键,还是可以使设备休眠。
配合使用wake lock:
其中有一些flag需要注意
/**
* Hold a wakelock that can be acquired in the AlarmReceiver and
* released in the AlarmAlert activity
*/
class AlarmAlertWakeLock {
private static PowerManager.WakeLock sCpuWakeLock;
/**
* 获取cpu锁
* @param context
*/
static void acquireCpuWakeLock(Context context) {
if (sCpuWakeLock != null) {
return;
}
PowerManager pm =
(PowerManager) context.getSystemService(Context.POWER_SERVICE);
sCpuWakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "AlarmClock");
sCpuWakeLock.acquire();
}
static void releaseCpuLock() {
if (sCpuWakeLock != null) {
sCpuWakeLock.release();
sCpuWakeLock = null;
}
}
}