Jetpack(六) 之 WorkManager

源码分析:WorkManager 源码分析

基本使用

WorkRequest,Data,WorkManager

单个任务基本使用

OneTimeWorkRequest

/**
     * 测试任务一,单个任务执行
     *
     * @param view
     */
    public void testBackgroundWork1(View view) {
        // 单一的任务 一次
        OneTimeWorkRequest oneTimeWorkRequest1;
        // 模拟数据
        Data sendData = new Data.Builder().putString("David", "九阳神功").build();

        //请求对象初始化
        oneTimeWorkRequest1 = new OneTimeWorkRequest
                .Builder(WorkManager1.class)
                .setInputData(sendData)
                .build();
        // 获取LiveData by UUId 建立Observe
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(oneTimeWorkRequest1.getId()).observe(this, new Observer() {
            @Override
            public void onChanged(WorkInfo workInfo) {
                Log.d(Config.TAG_WORKMANAGER, "Activity取到了任务回传的数据: "
                        + workInfo.getOutputData().getString("David"));
                Log.d(Config.TAG_WORKMANAGER, "状态:" + workInfo.getState().name());
                if (workInfo.getState().isFinished()) {
                    Log.d(Config.TAG_WORKMANAGER, "状态:isFinished=true 后台任务已经完成了...");
                }

            }
        });

        //请求对象加入队列
        WorkManager.getInstance(this).enqueue(oneTimeWorkRequest1);


    }

多个任务顺序执行

    public void testBackgroundWork2(View view) {

        // 单一的任务  一次
        OneTimeWorkRequest oneTimeWorkRequest2 = new OneTimeWorkRequest.Builder(WorkManager2.class).build();
        OneTimeWorkRequest oneTimeWorkRequest3 = new OneTimeWorkRequest.Builder(WorkManager3.class).build();
        OneTimeWorkRequest oneTimeWorkRequest4 = new OneTimeWorkRequest.Builder(WorkManager4.class).build();
        OneTimeWorkRequest oneTimeWorkRequest5 = new OneTimeWorkRequest.Builder(WorkManager5.class).build();

        // 顺序执行
        WorkManager.getInstance(this).beginWith(oneTimeWorkRequest2)
                .then(oneTimeWorkRequest3)
                .then(oneTimeWorkRequest4)
                .then(oneTimeWorkRequest5)
                .enqueue();


        // 把Request 存入集合 TODO 并发执行 
//        List oneTimeWorkRequests = new ArrayList<>();
//        oneTimeWorkRequests.add(oneTimeWorkRequest2); // 测试:没有并行
//        oneTimeWorkRequests.add(oneTimeWorkRequest3); // 测试:没有并行
//        WorkManager.getInstance(this).beginWith(oneTimeWorkRequests)
//                .then(oneTimeWorkRequest4)
//                .then(oneTimeWorkRequest5)
//                .enqueue();
        
    }

PeriodicWorkRequest,WorkManager,enqueue

定时任务

public void testBackgroundWork3(View view) {
        // 重复的任务  多次  循环  , 最少循环重复 15分钟
        PeriodicWorkRequest periodicWorkRequest =
                new PeriodicWorkRequest.Builder(WorkManager2.class, 10, TimeUnit.SECONDS).build();

        // 监听状态
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(periodicWorkRequest.getId())
                .observe(this, new Observer() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.d(Config.TAG_WORKMANAGER, "状态:" + workInfo.getState().name());
                        if (workInfo.getState().isFinished()) {
                            Log.d(Config.TAG_WORKMANAGER,  "状态:isFinished=true 同学们注意:后台任务已经完成了...");
                        }
                    }
                });

        WorkManager.getInstance(this).enqueue(periodicWorkRequest);
    }

带有约束条件
Constraints 加入约束条件.setConstraints(myConstraints)

@RequiresApi(api = Build.VERSION_CODES.M)
    public void testBackgroundWork4(View view) {
        // 约束条件,必须满足我的条件,才能执行后台任务 (在连接网络,插入电源 并且 处于空闲时)  内部做了电量优化(Android App 不耗电)
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED) // 网络链接中...
                .setRequiresCharging(true) // 充电中..
                .setRequiresDeviceIdle(true) // 空闲时.. (没有玩游戏)
                .build();

        /**
         * 除了上面设置的约束外,WorkManger还提供了以下的约束作为Work执行的条件:
         *  setRequiredNetworkType:网络连接设置
         *  setRequiresBatteryNotLow:是否为低电量时运行 默认false
         *  setRequiresCharging:是否要插入设备(接入电源),默认false
         *  setRequiresDeviceIdle:设备是否为空闲,默认false
         *  setRequiresStorageNotLow:设备可用存储是否不低于临界阈值
         */

        // 请求对象
        OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(WorkManager2.class)
                .setConstraints(myConstraints)
                .build();

        // 测试:监听状态
        // 监听状态
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.getId())
                .observe(this, new Observer() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.d(Config.TAG_WORKMANAGER,  "状态:" + workInfo.getState().name());
                        if (workInfo.getState().isFinished()) {
                            Log.d(Config.TAG_WORKMANAGER,  "状态:isFinished=true 同学们注意:后台任务已经完成了...");
                        }
                    }
                });

        // 加入队列
        WorkManager.getInstance(this).enqueue(request);
    }

多条件的约束

充电,空闲,网络连接,电量优化

@RequiresApi(api = Build.VERSION_CODES.M)
    public void testBackgroundWork7(View view) {
        // 约束条件,必须满足我的条件,才能执行后台任务 (在连接网络,插入电源 并且 处于空闲时)  内部做了电量优化(Android App 不耗电)
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED) // 网络链接中...
                .setRequiresCharging(true) // 充电中..
                .setRequiresDeviceIdle(true) // 空闲时.. (没有玩游戏)
                .build();

        // 请求对象
        OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(WorkManager2.class)
                .setConstraints(myConstraints) // TODO 3 约束条件的执行
                .build();
        WorkManager.getInstance(this) // TODO 1 初始化工作源码
                .enqueue(request); // TODO 2 加入队列执行
    }

Jetpack(一)Lifecycle和LiveData
JetPacks之Lifecycles原理
JetPack之 LifeCycle LiveData

Jetpack(二)之DataBinding

Jetpack(三) 之 Room 与 ViewModel
Jetpack 之 ViewModel 原理

Jetpack (四) 之 Navigation
Jetpack Navigation 原理浅析

JetPack (五)之 Paging 分页库

Jetpack(六) 之 WorkManager
Jetpack WorkManager 原理

你可能感兴趣的:(Jetpack(六) 之 WorkManager)