Android 使用SetExactAndAllowHileidle方法随机唤醒服务
我需要每60秒唤醒一次服务(例如) 服务将自身配置为使用以下代码唤醒:Android 使用SetExactAndAllowHileidle方法随机唤醒服务,android,service,background,alarmmanager,wakeup,Android,Service,Background,Alarmmanager,Wakeup,我需要每60秒唤醒一次服务(例如) 服务将自身配置为使用以下代码唤醒: private void rescheduleService() { // setup calendar Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.SECOND, 60); // setup intent Intent ser
private void rescheduleService() {
// setup calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.SECOND, 60);
// setup intent
Intent serviceGeofence = new Intent(this, ServiceGeofence.class); // this service
PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceGeofence, PendingIntent.FLAG_CANCEL_CURRENT);
// setup alarm
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
if(Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent);
} else if(Build.VERSION.SDK_INT >= 19){
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent);
} else {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent);
}
Log.i(TAG, "next alarm: " + calendar.toString());
Log.i(TAG, "alarm configured");
}
当手机充电或通过USB连接时,上述代码正常工作。它按预期每60秒执行一次。我可以在LogCat中看到它
但是,当我将手机从USB拔下时,服务会被随机唤醒(3或5分钟,甚至30分钟后)
我正在使用类似于setExactAndAllowHileIDLE
,setExacture
(取决于Android版本)的方法在配置设备时外部唤醒设备。但它只在设备连接到USB时工作
TL;博士以上代码为:
- 当设备连接到USB时:工作正常
- 当设备与USB断开连接时:无法按预期工作
基本上。。。如果sdk>=19,则需要使用serExact。不要使用SetExactAndAllowHileidle这真的很奇怪。。。你能告诉我你是如何使用“重新安排服务”方法的吗?即使这并没有回答你的问题,但也许你想尝试一下JobScheduler(在Android L中引入)和FirebaseJobDispatcher之类的类。我还需要调用setExactAndAllowHileidle(),正如你所读到的,这个方法在api 23和更高版本上使用,以便在设备处于睡眠区或空闲时发出警报。无论如何,我正在用Android Lolipop在设备上进行测试,这是一种精确的方法