从API 19开始,alarm的机制都是非准确传递,操作系统将会转换闹钟,来最小化唤醒和电池使用。
有一些新的API会支持严格准确的传递,见 setWindow(int, long, long, PendingIntent)和setExact(int, long, PendingIntent)。
targetSdkVersion在API 19之前应用仍将继续使用以前的行为,所有的闹钟在要求准确传递的情况下都会准确传递。
setRepeating 方法在 API 19开始将会失去原来的效果`
public static void setAlarmTime(Context context, long timeInMillis,String action, int time) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(action);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);
int interval = time;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//参数2是开始时间、参数3是允许系统延迟的时间
am.setWindow(AlarmManager.RTC, timeInMillis, interval, sender);
} else {
am.setRepeating(AlarmManager.RTC, timeInMillis, interval, sender);
}
}
public static void canalAlarm(Context context, String action) {
Intent intent = new Intent(action);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
}
在广播接收的地方
//因为setWindow只执行一次,所以要重新定义闹钟实现循环。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setAlarmTime(context, System.currentTimeMillis() + 15, "自定义action", 15);
}
这样就可以无线循环啦 ~~~~
这种无赖方法多用于socket即时通讯,或者定时任务提醒