当设备在Android中处于休眠状态时,AlarmManager警报不工作
我需要在每个时间段运行一段代码,即使应用程序被关闭或设备休眠 我正在使用当设备在Android中处于休眠状态时,AlarmManager警报不工作,android,alarmmanager,Android,Alarmmanager,我需要在每个时间段运行一段代码,即使应用程序被关闭或设备休眠 我正在使用AlarmManager来实现这一点,它有点工作,但当设备睡眠约五分钟时,服务将不再被调用。。。有人知道我做错了什么吗 这是我的密码: public class Profiler extends IntentService { public static final int ALARM_MANAGER_ID = 21436587; public Profiler() { super("Pr
AlarmManager
来实现这一点,它有点工作,但当设备睡眠约五分钟时,服务
将不再被调用。。。有人知道我做错了什么吗
这是我的密码:
public class Profiler extends IntentService {
public static final int ALARM_MANAGER_ID = 21436587;
public Profiler() {
super("Profiler");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
JodaTimeAndroid.init(getApplicationContext());
System.out.println("Testing profiles");
List<Profile> profiles = MainActivity.getStoredProfiles(getApplicationContext());
if (profiles != null) {
for (Profile profile : profiles) {
if(profile.check()) {
profile.set(getApplicationContext());
}
}
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent2 = new Intent(getApplicationContext(), Profiler.class);
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), ALARM_MANAGER_ID, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, DateTime.now().plusSeconds(10).getMillis(), pIntent);
}
}
应用程序是在11:31启动的,现在是11:40,正如您所看到的,代码的最后一次执行是在11:35,在此之前是11:32,3分钟,然后好像每5分钟调用一次
我以以下方式开始服务:
Intent bgServiceIntent = new Intent(getApplicationContext(), Profiler.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if(checkNotificationPolicy(getApplicationContext())) {
startService(bgServiceIntent);
}
} else {
startService(bgServiceIntent);
}
我正在使用的设备:华为P9 lite(VNS-L21)问题的原因很可能是 从其关于AlarmManager的文档中: 为了帮助安排警报,Android 6.0(API级别23)引入了 两个新的
AlarmManager
方法:setAndAllowHileId()
和
设置ExactAndAllowHileId()
。使用这些方法,您可以设置警报
即使设备处于休眠状态,也会触发
您应该根据API级别调用相应的AlarmManager
方法,以确保即使在设备处于休眠状态时,警报也会熄灭:
if (Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
alarmMillis, alarmIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP,
alarmMillis, alarmIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP,
alarmMillis, alarmIntent);
}
考虑以下因素:
无论是setAndAllowHileId()
还是setExactAndAllowHileId()
都不能
每个应用程序每9分钟发出一次以上的火灾警报
正如您所说,您正在华为设备上进行测试
华为(以及其他制造商)已经实施了某些电池节电功能,可以防止警报响起。你必须将你的应用程序添加到“受保护”的应用程序中
检查以下问题:&
不建议以编程方式执行此操作,一个合适的解决方案可能是在启动时警告用户(例如使用
AlertDialog
)在电池管理器中手动使您的应用程序“受保护”。使用Jobscheduler API而不是AlarmManagerJobSchedular不是一个合适的主意…可能会出现向后兼容性问题,可能存在向后兼容性问题。minTargetSDK将为21。
if (Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
alarmMillis, alarmIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP,
alarmMillis, alarmIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP,
alarmMillis, alarmIntent);
}