Android体系架构:WorkManager

WorkManager是Android自最新的支持包androidx引入的后台任务框架。和JobSchedule 相似,是JobSchedule 的改进。

WorkManager可实现:

一次性执行任务,链式执行任务,周期性执行任务,一定条件下(网络,电量)执行任务,设备重启后执行上次未完成任务等。

在Android studio中build.gradle引入WorkManager:

implementation "androidx.work:work-runtime:2.0.1"

因为Androidx和过去android的支持包不兼容,需要配置:

android.useAndroidX=true
android.enableJetifier=true

 

 

package zhangphil.app;

import android.content.Context;
import android.os.SystemClock;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import java.text.SimpleDateFormat;
import java.util.Date;


public class MyWorker extends Worker {
    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss:SSS");
    private Date mDate = new Date();

    public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        int n = getInputData().getInt(MainActivity.KEY, 1);

        System.out.println(n + "," + getId() + "开始任务doWork()");

        SystemClock.sleep(3000);

        mDate.setTime(System.currentTimeMillis());
        Data outputData = new Data.Builder()
                .putString(MainActivity.KEY, n + "@" + mSimpleDateFormat.format(mDate) + "#" + getId())
                .build();

        return Result.success(outputData);
    }

    @Override
    public void onStopped() {
        super.onStopped();

        System.out.println("任务onStop()");
    }
}
package zhangphil.app;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.Operation;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    public static String KEY = "KEY";
    private String TAG = "tag";
    private TextView text;
    private String string = "";
    private static int VALUE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.text);

        Data myData = new Data.Builder()
                .putInt(KEY, VALUE++)
                .build();

        //约束条件。
        Constraints constraints = new Constraints.Builder()
                .setRequiresBatteryNotLow(true)
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
                .build();

        OneTimeWorkRequest.Builder argsWorkBuilder = new OneTimeWorkRequest.Builder(MyWorker.class)
                .setConstraints(constraints)
                .setInitialDelay(1, TimeUnit.SECONDS)
                .setInputData(myData);

        OneTimeWorkRequest request = argsWorkBuilder
                .addTag(TAG)
                .build();

        System.out.println(request.getId() + "进入onCreate()");

        LiveData<List<WorkInfo>> liveData = WorkManager.getInstance().getWorkInfosByTagLiveData(TAG);

        liveData.observe(this, new Observer<List<WorkInfo>>() {
            @Override
            public void onChanged(List<WorkInfo> workInfos) {
                for (WorkInfo workInfo : workInfos) {
                    if (workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                        display(workInfo.getOutputData().getString(KEY));
                    }
                }
            }
        });

        Operation operation = WorkManager.getInstance()
                .enqueue(request);

        //取消任务。
        //WorkManager.getInstance().cancelWorkById(request.getId());
    }

    private void display(String s) {
        string = string + s + "\n";
        text.setText(string);
    }
}

WorkManager可以执行链式任务,假设有下面的任务链:

 

那么可以这么写链式任务:

WorkContinuation chain1 = WorkManager.getInstance()
  .beginWith(workA)
  .then(workB);

WorkContinuation chain2 = WorkManager.getInstance()
  .beginWith(workC)
  .then(workD);

WorkContinuation chain3 = WorkContinuation
  .combine(chain1, chain2)
  .then(workE);
chain3.enqueue();

 

相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页