I wrote this code:
public static Slider downloadStorageFile(String url, OnComplete<Integer> percentageCallback, OnComplete<String> filesavedCallback) {
final String filename = getNewStorageFilename();
ConnectionRequest cr = Rest.get(url).fetchAsBytes(response -> CN.callSerially(() -> filesavedCallback.completed(filename)));
cr.setDestinationStorage(filename);
Slider slider = new Slider();
slider.addDataChangedListener((int type, int index) -> {
CN.callSerially(() -> percentageCallback.completed(slider.getProgress()));
});
sliderBridgeMap.put(cr, slider);
SliderBridge.bindProgress(cr, slider);
return slider;
}
Basically, as you can guess, it asynchronously downloads a file, it offers two callbacks that will run on the EDT and it immediately returns a Slider that keep track of the download progress.
On Android, the download continues and ends even when the app is in background. On iOS, on the other hand, the app must remain active and foregrounded at all time.
Is it possible to complete the download even on iOS when the app goes to the background?
Alternatively, can I get ConnectionRequest.retry()
, which is automatically invoked by my network error handler when the app returns to foreground on iOS, to restart where the download arrived at, rather than restart it from scratch?
Even better, can I get both points 1 and 2?
This is problematic on Android too as the OS may suddenly kill your ongoing download when the system is constrained. E.g. in the developer tools just turn on the kill activities immediately and see your download die the moment you minimize the app.
Most devices don't do that but if a device is running in battery saving mode that might happen.
The solution is to use background fetch when going into the background. The problem is that this doesn't provide the nice sort of UI you would get with the regular foreground download so you need to pick and choose which one to use.
See the JavaDoc for the class here: https://www.codenameone.com/javadoc/com/codename1/background/BackgroundFetch.html
And the slightly out of date blog post on the subject: https://www.codenameone.com/blog/background-fetch.html