Android alarm is cancelled after closing the application

This is normal behaviour. If the user voluntarily force stop the applicaiton, then it should be stopped. Else, you are creating a virus like application.

If you really want, you could write another service which monitors if your other service is running and runs the service if the one is not running. But this will be another application and (you hope) the user wont kill this app using task manager.

Personally, I wouldn’t worry. If the user stopped it, they wanted to stop it. Don’t annoy the user.

I believe @GSree is wrong. There’s a simple way to achieve this. Just use a custom action. Here’s how:

First, define a custom action name, such as:

public static final String MY_ACTION = "com.sample.myaction"

Then create a BroadcastReceiver:

public class MyAlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(MY_ACTION)) {
            // Do something here
        }
    }    
}

Register the receiver on your AndroidManifest.xml:

<receiver android:name="com.sample.MyAlarmReceiver">
    <intent-filter>
        <action android:name="com.sample.myaction"/>
    </intent-filter>
</receiver>

Then, to setup the alarm, use the following PendingIntent:

Intent i = new Intent(MY_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);

There may be other ways to do it, but I tried this solution and the BroadcastReceiver gets called even if I force-quit my app from the shell.

Notice how this solution does not require you to create a service.

Leave a Comment