Set alarm from Android 4.4 Kitkat
Asked Answered
B

2

12

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);
}
Balladeer answered 7/11, 2013 at 16:38 Comment(0)
H
7

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.
Holcombe answered 27/11, 2013 at 13:52 Comment(0)
A
0

I downloaded 4.1.2 and uninstalled 4.4 from my ADT. I set "Build Target" to 4.1.2 and cleaned and rebuilt my app and have reinstalled apk to mobile.

However, the behavior is still inexact.

I paste the output from adb shell dumpsys alarm below:

RTC_WAKEUP #0: Alarm{426941b0 type 0 net.coolbie.alarmclock}

   type=0 when=+4m46s480ms repeatInterval=0 count=0

   operation=PendingIntent{42553668: PendingIntentRecord{42a6cc38 net.coolbie.alarmclock broadcastIntent}}

You can see "when" is +4m up there, but which triggerTime is just 8 seconds.

long triggerTime = calendar.getTimeInMillis();
long currentTime = System.currentTimeMillis();
Toast.makeText(mContext, "gap is:"+(triggerTime-currentTime)/1000,Toast.LENGTH_LONG).show(); 
Intent intent = new Intent(mContext.getApplicationContext(), AlarmReceiver.class);  
PendingIntent pendIntent = PendingIntent.getBroadcast(mContext.getApplicationContext(),  
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);  
mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendIntent);
Atop answered 4/1, 2014 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.