Is it possible to do a repeated task even if app is killed from Task Manager?

635 views Asked by At

I've created an AlarmManager to call a BroadcastReceiver to make a request to a server every INTERVAL seconds.

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent intent = PendingIntent.getBroadcast(this, 0, new Intent(this, SendLogReceiver.class), 0);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, intent);

And this is the BroadcastReceiver:

public class SendLogReceiver extends BroadcastReceiver {
    private static final String TAG = SendPositionReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Sending position to server");
    }
}

It works even when app is in background, but when I close the app though Task Manager (by swiping) the AlarmManager dies and no more signals are received.

Is there any way to achieve that this BroadcastReceiver will continue working whenever the apps is killed?

Thanks

1

There are 1 answers

4
CommonsWare On

I do not know what "Task Manager" you are referring to.

The standard Android recent-tasks list, and third-party task managers you get from the Play Store, do not affect scheduled alarms.

There appear to be some devices, where the device manufacturer has pre-installed some separate "task manager" app, where that app does the equivalent of a "force stop" that you ordinarily can only do from a button in the app's page in Settings. If the user "force stops" the app, all alarms are unscheduled, and the app will not run again until the user manually runs it from the home screen launcher. There is nothing that you can do about that, though you are welcome to complain to your device manufacturer that their developers are idiots for making "force stop" that easy to do.

You can use the adb shell dumpsys alarm command to determine whether or not your alarm was truly unscheduled.

Bear in mind that on Android 5.1, a polling period of 1000ms is not supported. Anything less than 60000ms will be rounded up to 60000ms.

Also bear in mind that on Android M, your app will not run very much in the background anyway. Consider the use of AlarmManager as a "nice to have" sort of capability, rather than something that you can rely upon.