I need to upload the data to the server in a different thread (not on the main thread). I have tried WorkManager to do this job like below. But WorkManager is not getting triggered every time I background the app. How can I send the data to the server in a different thread while the app goes to the background every time?
@Override
public void onCreate() {
...
mRequest = new OneTimeWorkRequest.Builder(UploaddWorker.class).setConstraints(
new Constraints.Builder().setRequiredNetworkType(
NetworkType.CONNECTED).build()).build();
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onAppBackgrounded() {
//App in background
Log.e(TAG, "onAppBackgrounded");
mWorkManager.enqueue(mRequest);
}
When you enqueue the work is possible for it to start. It does not mean: "start now". For a work to start all the constraints must be satisfied. It depends on a lot of stuff and some of the constraints do not depend on your input, but also on battery optimization, etc.
If you want to start now go with a Service. Here you can read more about Background execution and how to pick:
https://developer.android.com/guide/background https://developer.android.com/guide/components/services
If you want to go in the direction of the WorkManager you need to read about StandbyBuckets. Also, try to debug the JobScheduler and see why a work is not running:
https://developer.android.com/topic/performance/appstandby https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging
Also, you need to understand Battery optimization:
https://developer.android.com/training/monitoring-device-state/doze-standby
And how to disable it:
And this:
https://developer.android.com/topic/performance/power/power-details