0

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);
    }
4

1 回答 1

1

当您排队时,工作就可以开始了。这并不意味着:“现在开始”。要开始工作,必须满足所有约束条件。这取决于很多东西,其中一些约束不取决于您的输入,还取决于电池优化等。

如果您想立即开始使用服务。在这里您可以阅读更多关于后台执行以及如何选择的信息:

https://developer.android.com/guide/background https://developer.android.com/guide/components/services

如果你想朝着 WorkManager 的方向前进,你需要阅读 StandbyBuckets。此外,尝试调试 JobScheduler 并查看工作未运行的原因:

https://developer.android.com/topic/performance/appstandby https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging

此外,您需要了解电池优化:

https://developer.android.com/training/monitoring-device-state/doze-standby

以及如何禁用它:

https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases

和这个:

https://developer.android.com/topic/performance/power/power-details

于 2021-08-17T12:19:10.563 回答