Android WorkManager not starting the worker
Asked Answered
A

0

9

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

Acetylene answered 11/3, 2020 at 21:57 Comment(4)
Try to remove @NonNull annotation from MyWorker constructor. Builder operates with it by reflection, this may cause an issue.Detain
Thanks @AntonProkopov, but it doesn't workAcetylene
Did you ever figure it out? Or did you choose a different solution? Thx.Outward
Is your MyWorker an inner class? https://mcmap.net/q/395023/-android-work-manager-quot-could-not-instantiate-worker-quotPasco

© 2022 - 2024 — McMap. All rights reserved.