如何使用
setallowWhileIdle
方法来完成AlarmManager
中的重复任务,因为我认为这是克服打瞌睡模式的唯一方法。
我需要在重复模式下工作 24*7 任务,有没有任何例子请帮助我是 android 新手
private void scheduleAlarm() {
try{
Intent intent = new Intent(getApplicationContext(), KeepAliveAlarmReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
KeepAliveAlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_MUTABLE);
long firstMillis = System.currentTimeMillis();// alarm is set right away
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP,firstMillis,60000, pIntent);
System.out.println("enters into alarm manager");
}catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
我需要在 setallowwhileIdle 方法上这样做,它不支持重复任务计时器。
请阅读@lyc001 的这篇文章。 Android - 空闲时允许重复闹钟
它说
AlarmManager 中唯一可用的 API Android 23 是 setExactAndAllowWhileIdle 和 setAndAllowWhileIdle 这不是为了重复闹钟。
您应该使用这些 API 中的任何一个,并“在每次触发警报时重新安排警报”。 因此,一个警报会注册另一个警报,依此类推。
这是让您的生活更轻松的代码!
首次注册(MainActivity.java)
AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmRBActivity.class);
boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), 007,
intent,
PendingIntent.FLAG_NO_CREATE) != null);
if(!alarmUp){
long triggerTime = intent
.getLongExtra("TRIGGER_TIME", System.currentTimeMillis());
triggerTime += TimeUnit.MINUTES.toMillis(2);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 007, intent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}
Log.e("alarm", "Alarm registered!");
}else{
Log.e("alarm", "Alarm already registered!");
}
触发时注册/循环注册(AlarmBRActivity.java)
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 007, AlarmIntent, 0);
long triggerTime = intent
.getLongExtra("TRIGGER_TIME", System.currentTimeMillis());
triggerTime += TimeUnit.MINUTES.toMillis(2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}