Android WorkManager not starting the worker

时光总嘲笑我的痴心妄想 提交于 2020-04-17 20:04:39

问题


I want to download certain files from the server at the start of the app .So I tried using Work Manager which gets enqueued from my custom Application class.But the Worker class is not getting triggered and the state is only ENQUEUED and not going to RUNNING.Below is my code:

Application class:

@Override
public void onCreate() {
    Constraints constraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            //.setRequiresStorageNotLow(true)
            //.setRequiresBatteryNotLow(true)
            .build();

    OneTimeWorkRequest request = new OneTimeWorkRequest
            .Builder(MyWorker.class)
            //.setConstraints(constraints)
            //.setInitialDelay(1,TimeUnit.SECONDS)
            .addTag("download")
            .build();

    WorkManager.getInstance(getApplicationContext()).getWorkInfoByIdLiveData(request.getId()).observeForever(new Observer<WorkInfo>() {
        @Override
        public void onChanged(WorkInfo workInfo) {
            if (workInfo == null) {
                Log.d("download", "workInfo == null");
            } else {
                Log.d("download", "workInfo != null: " + workInfo.getState().toString());//This is giving ENQUEUED once..thats it
            }
        }
    });
    WorkManager.getInstance(getApplicationContext()).enqueue(request);
}

MyWorker class

public class MyWorker extends Worker {

public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
    //Some file to download 
}
}

build.gradle:

implementation "androidx.work:work-runtime:2.3.2"

Things i have tried:

I tried adding an interval and also remove constraints, but then also, MyWorker is not triggered.

I have seen many SOF posts as given below but it didn't help me:

Worker manager: not start work in enqueue

Why workers in work manager still in ENQUEUED state?

Android WorkManager doesn't trigger one of the two scheduled workers

来源:https://stackoverflow.com/questions/60644939/android-workmanager-not-starting-the-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!