AlarmManager do not work when screen is locked on Android v4

1.9k views Asked by At

I can't get AlarmManager to work when screen is locked. The app works just fine on my Sony Ericsson Xperia Active with Android 2.3.4, regardless of if the screen is locked or not. I always see the debug message onReceive() in LogCat. But when I try to run the app on newer devices with newer versions of Android, e.g Samsung Galaxy Xcover2 with android 4.1.2, the app only works as long as the screen is on. I see debug message in LogCat for onReceive() only as long the screen is on. I see no debug messages when the screen is locked and the app stop working. I have tried other devices with the same problem. The common denominator seem to be(?) Android version.

Manifest

....

<service
android:name=".MyGPSService"
android:enabled="true"
android:exported="false" >
</service>

<receiver android:name=".MyAMReceiver" />

</application>

</manifest>

Main activity

....

public void onResume()  {
super.onResume();
// PendingIntent Broadcast from AlarmManager
Intent intent = new Intent(this, MyAMReceiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(this, 112358, intent, PendingIntent.FLAG_CANCEL_CURRENT);

// Registering pending intent with AlarmManager
AlarmManager alarmmanager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmmanager.cancel(pendingintent); // Cancel any existing alarms
alarmmanager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000,60000, pendingintent); // Delay first trigger 10s, timer interval 60s

Receiver class

....

public class MyAMReceiver extends BroadcastReceiver {
public MyAMReceiver() {
}


@Override
public void onReceive(Context context, Intent intent) {

//DEBUG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Log.d("MyAMReceiver", "onReceive()");

// Wake CPU from sleep if unit screen is locked
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();

// Start service
Intent intentS = new Intent(context, MyGPSService.class);
context.startService(intentS);

}
}
1

There are 1 answers

1
mrelemji On

Changed my code to this after reading the above:

alarmmanager.setRepeating(AlarmManager.ELAPSE_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+10000,60000, pendingintent);

The Samsung Android 4.1 is still refusing to fire AlarmManager(?) when sleeping. Still works on Sony Android 2.3 though.

But according to Android documentation on SystemClock it shouldn't make any difference: "The AlarmManager can trigger one-time or recurring events which occur even when the device is in deep sleep or your application is not running. Events may be scheduled with your choice of currentTimeMillis() (RTC) or elapsedRealtime() (ELAPSED_REALTIME), and cause an Intent broadcast when they occur."

http://developer.android.com/reference/android/os/SystemClock.html