服务随机唤醒,并使用setExactandallowwhileidle方法



我需要每60秒醒来一次服务。

服务配置自己以使用以下代码唤醒:

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分钟后(。

我正在使用setExactAndAllowWhileIdlesetExact(取决于Android版本(等方法在我配置的时间中大量唤醒设备。但是,只有在设备连接到USB时才起作用。

tl; dr;上面的代码:

  • 当设备连接到USB时:工作正常。
  • 当设备与USB断开时:
  • 无法正常工作。

对发生的事情有任何想法吗?

"注意:以API 19(Kitkat(警报传递开始是不精确的:OS将移动警报,以最大程度地减少唤醒和使用电池的使用。有新的API支持需要严格交付保证的申请;请参阅setWindow(int,长,长,垂直(和setExact(int,long,pendingintent(。TargetsDkversion比API 19的应用程序将继续看到以前的行为,其中所有警报在要求时准确地传递了所有警报。"

基本上...如果SDK> = 19您需要使用Serexact。不要使用setExActandallowwhileIdle

相关内容

  • 没有找到相关文章

最新更新