TechPosts

BackgroundFetchTask

The codename one background fetch service API allows you to poll data sources (over a network or locally) periodically for data updates. This polling will occur when the app is running in the foreground on all platforms. Additionally, some platforms will continue to execute your fetch task periodically while the app is in the background. You can find out, at runtime whether the device supports true background fetch by calling Display.getBackgroundFetchSupport() which will return either Display.BACKGROUND_FETCH_SUPPORT_FOREGROUND or Display.BACKGROUND_FETCH_SUPPORT_BACKGROUND.

Usage

Display.getInstance().startBackgroundFetchService(new BackgroundFetchTask() {

    /**
     * Just a null perform fetch that never loads any data.
     * This method must return one of RESULT_NEW_DATA, RESULT_NO_DATA,
     * or RESULT_FAIL.
     */
    @Override
    public int performFetch() {
        System.out.println("In performFetch()");
        return BackgroundFetchTask.RESULT_NO_DATA;

        // Note, you could also perform a network request here, but
        // it must be performed synchronously as the method
        // must return an accurate value when the network
        // request is done.
    }

    /**
     * Returns the preferred interval in seconds in which the update should
     * run. When running in the foreground the actual interval will be pretty
     * close to this preferred interval.  When in the background, there are
     * no guarantees. E.g. on iOS the OS will only fetch new data between 20
     * and 40 times per day per user.
     *
     * Return 0 to automatically set to the OS minimum value (when in
     * foreground, 0 will be rounded up to 1 hour).
     */
    @Override
    public int getPreferredInterval() {
        return 5000;
    }

});

Build Hint on iOS

If you want to support true background fetch on iOS, you must include the build hint ios.background_modes=fetch

Note
The ios.background_modes build hint can accept more than one background mode separated by commas. See full list of values here.

Time Limits

performFetch() is given a maximum running time of 30 seconds on iOS, and the faster the better. If it returns faster, then the OS will call it more frequently. If it returns slower, then the OS will throttle it, and call performFetch() less often.