Showing detailed progress for running WorkManager workers

前端 未结 2 412
无人及你
无人及你 2020-12-19 05:39

I want to replace the job scheduling aspect of my existing data syncing system with the new JetPack WorkManager (link to codelabs) component (in a sandbox branch of the app)

相关标签:
2条回答
  • 2020-12-19 06:28

    Natively Supported

    implementation 'androidx.work:work-runtime:2.3.4'
    

    Report progress on Worker:

    public class FooWorker extends Worker {
    
        public FooWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
            super(context, workerParams);
        }
    
        @NonNull
        @Override
        public Result doWork() {
            try {
                setProgressAsync(new Data.Builder().putInt("progress", 0).build());
                Thread.sleep(1000);
                setProgressAsync(new Data.Builder().putInt("progress", 50).build());
                Thread.sleep(1000);
                setProgressAsync(new Data.Builder().putInt("progress", 100).build());
    
                return Result.success();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return Result.failure();
            }
        }
    }
    

    Observe progress of Worker:

    WorkManager.getInstance(context).getWorkInfosForUniqueWorkLiveData("test").observe(lifecycleOwner, new Observer<List<WorkInfo>>() {
            @Override
            public void onChanged(List<WorkInfo> workInfos) {
                if (workInfos.size() > 0) {
                    WorkInfo info = workInfos.get(0);
                    int progress = info.getProgress().getInt("progress", -1);
                    //Do something with progress variable
                }
    
            }
        });
    

    ListenableWorker now supports the setProgressAsync() API, which allows it to persist intermediate progress. These APIs allow developers to set intermediate progress that can be observed by the UI. Progress is represented by the Data type, which is a serializable container of properties (similar to input and output, and subject to the same restrictions).

    See Android Documentation

    0 讨论(0)
  • 2020-12-19 06:29

    The best way to do it is to write intermediate progress to your own data store and expose a LiveData<>. We are considering adding this feature in a future alpha.

    0 讨论(0)
提交回复
热议问题