Frage

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);
}
War es hilfreich?

Lösung

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.

Andere Tipps

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);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top