AlarmManager not working as expected in sleep mode

2019-02-09 11:04发布

I am using an AlarmManager in a Service to be triggered every minute.

    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0,
            getUpdateServiceIntent(mContext), PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    // Cancel any pending Intent
    am.cancel(pendingIntent);

    // Set a new one
    am.set(AlarmManager.RTC_WAKEUP, 60000, pendingIntent);

On the Samsung S5 Neo : When the screen is active, it is working as expected. When the screen is off, it is triggered every 5 minutes (instead of one).

I try this exact same code on S5 Mini (with Android 4.4), Nexus 5 5.1 and Nexus 5 6.0, this code is working fine.

targetSdkVersion is 19.

Any idea how to keep the AlarmManager working correctly when screen is off ? The delay is still 5 minutes, even if I ask for 30 seconds.

EDIT : I also tried the 'setExact' method, but it didn't change anything. Still have a 5 minutes interval between each alarm.

1条回答
祖国的老花朵
2楼-- · 2019-02-09 11:55

You should probably use

AlarmManager#setExact(int type, long triggerAtMillis, PendingIntent operation)

instead of

AlarmManager#set(int type, long triggerAtMillis, PendingIntent operation))

Take a look

From google :

AlarmManager#set(int type, long triggerAtMillis, PendingIntent operation))

Note: Beginning in API 19, the trigger time passed to this method is treated as inexact: the alarm will not be delivered before this time, but may be deferred and delivered some time later. The OS will use this policy in order to "batch" alarms together across the entire system, minimizing the number of times the device needs to "wake up" and minimizing battery use. In general, alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.

Edit :

What i am using for an alarm application :

Manifest :

<uses-permission android:name="android.permission.WAKE_LOCK"/>

Java Code :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(nextAlarm.getTimeInMillis(), pendingIntent);
  alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  alarmManager.setExact(android.app.AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), pendingIntent);
}else {
  alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), pendingIntent);
}
查看更多
登录 后发表回答