Slagathor
Slagathor

Reputation: 892

Only want Alarm to die when removed from Recent Apps or user forced killed

I have an application that does something in a service triggered by an alarm every 10 minutes while the app is in the background. I want the Alarm to keep going off even if the OS kills the app (So its dead and have to relaunch) and only kill it if the user actually removes the app from recent apps or force kills it from settings (or is logged off but that already works). I have tried many different approaches, latest I tried this http://www.dotkam.com/2011/01/10/android-prefer-alarms-and-intent-receivers-to-services/ without any luck. My Alarm looks like this.

    if(ActivityLifecycleHandler.isApplicationInForeground()) {
        return;   // If App is in foreground do not start alarm!
    }

    String alarm = Context.ALARM_SERVICE;
    AlarmManager am = ( AlarmManager ) context.getSystemService( alarm );

    Intent intent = new Intent(locationBroadcastAction);
    PendingIntent pi = PendingIntent.getBroadcast( context.getApplicationContext(), 0, intent, 0 );

    int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;

    // Set trigger time to 0, because want to fire off the first one instantly
    am.setRepeating( type, 0, ONE_MINUTE, pi );     

And the BroadcastReceiver:

public class LocationBroadcastReceiver extends BroadcastReceiver{

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

    Intent myIntent = new Intent( context, LocationService.class );
    context.startService( myIntent );
}
}

Any idea of what I am doing wrong? Everything works fine until the OS kills the app.

Upvotes: 0

Views: 273

Answers (1)

Philippe Banwarth
Philippe Banwarth

Reputation: 17755

The alarm should goes off if the app was killed, even if if was removed from the recent app (but not if it was force-stopped).

It is actually the whole point of using the AlarmManager :

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

You can see if the alarm is still there with :

adb shell dumpsys alarm 

What is probably happening is that the device is woken up to receive the alarm, but fall asleep again as soon as the receiver finishes, before the service can start.

The receiver should take a wake lock (to be released by the service). The support library provides a WakefulBroadcastReceiver which does exactly that :

Helper for the common pattern of implementing a BroadcastReceiver that receives a device wakeup event and then passes the work off to a Service, while ensuring that the device does not go back to sleep during the transition.

Upvotes: 1

Related Questions