Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set alarm from Android 4.4 Kitkat

In Android 4.4 APIs page I read:

When you set your app's targetSdkVersion to "19" or higher, alarms that you create using either set() or setRepeating() will be inexact.

[CUT]

This inexact batching behavior applies only to updated apps. If you've set the targetSdkVersion to "18" or lower, your alarms will continue behave as they have on previous versions when running on Android 4.4.

In my application I need exact time alarm and I updated targetSdkVersion to "19". Is it correct the following code? Also if I set targetSdkVersion to "19" in phone with previous versions does the "old" method AlarmManager.set continue to work in the same way?

private void setAlarm (long ms){
    final AlarmManager am = (AlarmManager) mCtx.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, BroadcastReceiverAlarm.class);
    PendingIntent pi = PendingIntent.getBroadcast(this, ALARM_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
        am.set(AlarmManager.RTC, ms, pi);
    } else {
        setAlarmFromKitkat(am, ms, pi);
    }
}

@TargetApi(19)
private void setAlarmFromKitkat(AlarmManager am, long ms, PendingIntent pi){
    am.setExact(AlarmManager.RTC, ms, pi);
}
like image 512
crbin1 Avatar asked Nov 07 '13 16:11

crbin1


1 Answers

Yes this is correct. Google failed to describe in more details:

  1. for targetSDKVersion<19, "set" will be exact no matter the device is running on KitKat or earlier versions.
  2. for targetSDKVersion>=19, "set" will be exact for device running < KitKat. But it will be inexact for device running KitKat.
like image 96
Phuah Yee Keat Avatar answered Nov 08 '22 22:11

Phuah Yee Keat