GcmNetworkManager OneoffTask called very often, Problems detecting network state changes on Android N

198 views Asked by At

I need that the app wakes up when the network state changes, even when not running in the background.

Before Android N, I had a network state change registered in the Manifest

<receiver android:name=".receiver.NetworkStateChangeReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

This is deprecated for Android N. I am aware that it is still possible to register this not in the Manifest but programmatically but then it just works as long as the app is alive in the background. -> But I need a solution that works also when the app is completely closed.

What I tried now is having a Service extending the GcmTaskService which looks like this:

public class NetworkChangeService extends GcmTaskService {

    public static String TAG = "networkChangeTask";
    private static long ONE_DAY_IN_SECONDS = 3600L * 24L;

    @Override
    public int onRunTask(TaskParams taskParams) {

        // do my task here like syncing stuff

        scheduleTask(this);
        return GcmNetworkManager.RESULT_SUCCESS;
    }

    public static void scheduleTask(Context context) {
        OneoffTask task = new OneoffTask.Builder()
                .setService(NetworkChangeService.class)
                .setTag(TAG)
                .setExecutionWindow(1L, ONE_DAY_IN_SECONDS)
                .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
                .setPersisted(true)
                .setUpdateCurrent(true)
                .build();

        GcmNetworkManager.getInstance(context).schedule(task);
    }

    @Override
    public void onInitializeTasks() {
        super.onInitializeTasks();
        // Re-schedule periodic task on app upgrade.
        scheduleTask(this);
    }
}

The basic idea is to schedule a task that triggers on network change, and if it does re-schedule that task for when the network state changes again in the future.

This seems to work on a first look, the onRunTask(TaskParams taskParams)is called every time the network changes when I debug this. But when I leave my android phone locked on my desk one hour (and it is connected to a wifi) and is not moved or anything the task is called about 40 times within one hour!

Can anyone explain to me why this task is called so often? Does the network state really change that often within one hour or am I using the OneoffTask wrong?

Additional question: I generally want to perform a task every time the devices switches from not connected to a connected status, I am not forced to use the GcmNetworkManager. Is there a better way to achieve this on android (without using pushes or any external service)?

0

There are 0 answers