问题
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