Showing detailed progress for running WorkManager workers

前端 未结 2 510
无人及你
无人及你 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>() {
            @Override
            public void onChanged(List 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

提交回复
热议问题