Reputation: 3494
I'm using an AlarmManager
to send a broadcast while the screen is off. This works fine on most devices, but on some (e.g. Samsung Galaxy S4), it takes 30, 40, or even 120 seconds instead of the specified 20s until the broadcast is received. I don't have access to the devices on which this is happening so I can't check the logcat.
This is how I'm setting up the AlarmManager
:
AlarmManager mAlarmManager=(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
long mInterval = 20 * 1000;
Intent i = new Intent();
i.setAction(MY_ACTION);
mPendingIntent = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + mInterval, mPendingIntent);
And this is the receiver, registered in the manifest:
private class MyIntentReceiver extends BroadcastReceiver {
private static final String TAG = "MyIntentReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MY_ACTION)) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
Log.e(TAG, "onReceive");
//Carry out my action...
wl.release();
}
}
}
Upvotes: 2
Views: 913
Reputation: 17850
The behaviour of AlarmManager changed with the arrival of API 19. Many wasted hours on troubleshooting an app that used to work just fine before reading the updated Javadoc.
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see
setWindow(int, long, long, PendingIntent)
andsetExact(int, long, PendingIntent)
. Applications whosetargetSdkVersion
is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
Upvotes: 0
Reputation: 3494
I changed the parameters of the AlarmManager.set()
method to AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
instead of my initial AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
based on CommonsWare's sample, and it now works on the S4, too. I don't know why ELAPSED_REALTIME_WAKEUP
isn't working, as it specifically carries WAKEUP
in its name and works on all other devices on which I've tested it.
Upvotes: 0