WorkManager

1.WorkManager

简介

2.使用

2.1 定义Worker

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

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

import com.alibaba.fastjson.JSON;
import com.tencent.mmkv.MMKV;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.ReadableByteChannel;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadWorker extends Worker {
    private static final int MAX_BUFFER_SIZE = 4096;
    
    public DownloadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        // 下载进度初始化
        // 观察工作器的中间进度
        // https://developer.android.com/topic/libraries/architecture/workmanager/how-to/intermediate-progress
        setProgressAsync(new Data.Builder().putDouble(DOWNLOAD_FILE_PROGRESS, 0).build());
    }
    
    @NonNull
    @Override
    public Result doWork() {
        Log.e("currentThread", Thread.currentThread().getName());
        String downloadUrl = getInputData().getString(DOWNLOAD_URL);
        if (downloadUrl != null) {
            OkHttpClient client =
                    new OkHttpClient.Builder()
                            .connectTimeout(5, TimeUnit.SECONDS)
                            .readTimeout(5, TimeUnit.SECONDS)
                            .build();
            Request request = new Request.Builder().url(downloadUrl).build();
            Response response;
            try {
                response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    return Result.retry();
                } else {
                    if (response.body() != null) {
                        String fileName = DownloadFileHeaderParse.findFilename(response.headers(), downloadUrl, true, DOWNLOAD_DEFAULT_FILE_NAME);
                        String parentFilePath = getParentFile().getAbsolutePath() + File.separator + DOWNLOAD_FOLDER_NAME;
                        String saveFilePath = parentFilePath + File.separator + fileName;
                        long contentLength = response.body().contentLength();
                        String etag = DownloadFileHeaderParse.findFileEtag(response.headers());
                        String lastModified = DownloadFileHeaderParse.findFileLastModified(response.headers());
                        
                        File downloadFolder = new File(parentFilePath);
                        if (!downloadFolder.exists() && !downloadFolder.isDirectory()) {
                            downloadFolder.mkdir();
                        }
                        
                        DownloadedModel downloadedModel = doCheckSameFileWork(contentLength, etag, lastModified);
                        if (downloadedModel != null && downloadedModel.isSameFile()) {
                            String jsonObjectString = JSON.toJSONString(downloadedModel);
                            Data output = new Data.Builder()
                                    .putString(DOWNLOAD_MODEL_JSON_STRING, jsonObjectString)
                                    .build();
                            return ListenableWorker.Result.success(output);
                        } else {
                            Data output =
                                    saveFile(downloadUrl, response, parentFilePath, saveFilePath, contentLength, etag, lastModified);
                            return ListenableWorker.Result.success(output);
                        }
                    } else {
                        Data output =
                                new Data.Builder()
                                        .putString(DOWNLOAD_FILE_EXCEPTION, "response.body() is null")
                                        .build();
                        return ListenableWorker.Result.failure(output);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Data output = new Data.Builder().putString(DOWNLOAD_FILE_EXCEPTION, e.getMessage()).build();
                return ListenableWorker.Result.failure(output);
            }
        } else {
            return ListenableWorker.Result.success();
        }
    }
    
    @NonNull
    private Data saveFile(
            String downloadUrl,
            Response response,
            String parentFilePath,
            String saveFilePath,
            long contentLength,
            String eTag,
            String lastModified)
            throws Exception {
        int written = 0;
        InputStream inputStream = response.body().byteStream();
        final File outputFile = new File(saveFilePath);
        // 打开FileChannel
        // https://www.programcreek.com/java-api-examples/?class=java.io.FileOutputStream&method=getChannel
        RandomAccessFile randomAccessFile = new RandomAccessFile(outputFile, "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        final FileLock fileLock = fileChannel.tryLock();
        if (fileLock == null) {
            throw new RuntimeException("Failed to acquire lock");
        } else {
            try {
                final ReadableByteChannel in = Channels.newChannel(new BufferedInputStream(inputStream));
                final ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_BUFFER_SIZE);
                while (in.read(byteBuffer) != -1) {
                    byteBuffer.flip();
                    written += fileChannel.write(byteBuffer);
                    // 下载进度
                    setProgressAsync(
                            new Data.Builder()
                                    .putDouble(DOWNLOAD_FILE_PROGRESS, (written * 1.0 / contentLength))
                                    .build());
                    byteBuffer.clear();
                }
                // 下载完成
                setProgressAsync(new Data.Builder().putDouble(DOWNLOAD_FILE_PROGRESS, 1).build());
            } finally {
                fileLock.release();
                fileChannel.close();
            }
        }
        DownloadedModel downloadedModel = new DownloadedModel();
        downloadedModel.setDownloadUrl(downloadUrl);
        downloadedModel.setContentLength(contentLength);
        downloadedModel.setLastModified(lastModified);
        downloadedModel.seteTag(eTag);
        downloadedModel.setParentPath(parentFilePath);
        downloadedModel.setFilePath(saveFilePath);
        // downloadedModel.setMd5(Md5Util.get32LittleMD5Str(etag + lastModified + contentLength));
        MMKV kv = MMKV.defaultMMKV();
        String jsonObjectString = JSON.toJSONString(downloadedModel);
        kv.encode(DOWNLOAD_SUCCESS_CONFIG, jsonObjectString);
        return new Data.Builder()
                .putString(DOWNLOAD_MODEL_JSON_STRING, jsonObjectString)
                .build();
    }
    
    public DownloadedModel doCheckSameFileWork(
            long contentLength,
            String etag,
            String lastModified) {
        MMKV kv = MMKV.defaultMMKV();
        String downloadConfig = kv.decodeString(DOWNLOAD_SUCCESS_CONFIG);
        DownloadedModel downloadedModel = JSON.parseObject(downloadConfig, DownloadedModel.class);
        if (downloadConfig == null || downloadedModel == null) {
            return null;
        }
        String oldSavePath = downloadedModel.getFilePath();
        Long oldContentLength = downloadedModel.getContentLength();
        String oldETag = downloadedModel.geteTag();
        String oldLastModified = downloadedModel.getLastModified();
        if (!TextUtils.isEmpty(oldSavePath)) {
            downloadedModel.setSameFile(
                    contentLength == oldContentLength
                            && !TextUtils.isEmpty(oldETag)
                            && !TextUtils.isEmpty(etag)
                            && oldETag.equals(etag)
                            && !TextUtils.isEmpty(oldLastModified)
                            && !TextUtils.isEmpty(lastModified)
                            && oldLastModified.equals(lastModified));
            return downloadedModel;
        } else {
            return null;
        }
    }
}

2.2 注册监听

  • 2.2.1 输入Data
  • 2.2.2 Constraints 约束
  • 2.2.3 WorkRequest
  • 2.2.4 执行
  • 2.2.5 监听
  • 2.2.6 取消任务
public void downloadingFile(String downUrl, @NonNull LifecycleOwner owner, boolean needUnZip) {
        Data data = new Data.Builder()
                .putString(DOWNLOAD_URL, downUrl)
                .build();
        Constraints constraints =
                new Constraints.Builder()
                        //.setRequiredNetworkType(NetworkType.CONNECTED)
                        .build();
        
        OneTimeWorkRequest downloadWorker =
                new OneTimeWorkRequest.Builder(DownloadWorker.class)
                        .setConstraints(constraints)
                        /*.setBackoffCriteria(
                                BackoffPolicy.LINEAR, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)*/
                        //.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
                        .setInputData(data)
                        .build();
        // https://proandroiddev.com/step-by-step-guide-to-download-files-with-workmanager-b0231b03efd1
        
        WorkManager.getInstance(ContextProvider.get().getContext())
                .enqueueUniqueWork(DOWNLOAD_FILE_UNIQUE_TAG, ExistingWorkPolicy.KEEP, downloadWorker);
        WorkManager.getInstance(ContextProvider.get().getContext())
                .getWorkInfoByIdLiveData(downloadWorker.getId())
                .observe(
                        owner,
                        workInfo -> {
                            Log.e("downloadWorker", workInfo.toString());
                            switch (workInfo.getState()) {
                                case RUNNING: {
                                    Data progress = workInfo.getProgress();
                                    double value = progress.getDouble(DOWNLOAD_FILE_PROGRESS, 0.0);
                                    Log.e("downloadWorker", "progress:" + value);
                                }
                                break;
                                case SUCCEEDED: {
                                    Data isSuccessfulData = workInfo.getOutputData();
                                    String result = isSuccessfulData.getString(DOWNLOAD_MODEL_JSON_STRING);
                                    DownloadedModel downloadedModel = JSON.parseObject(result, DownloadedModel.class);
                                    String savePath = downloadedModel.getFilePath();
                                    String parentFilePath = downloadedModel.getParentPath();
                                    if (needUnZip) {
                                        unZipFileWorkerDownloadingFile(downUrl, savePath, parentFilePath, owner);
                                    }
                                    downloadedSuccessMessage.postValue(result);
                                    Log.e("downloadWorker", "result = " + result);
                                }
                                break;
                                case FAILED: {
                                    MMKV kv = MMKV.defaultMMKV();
                                    String unZipConfig = kv.decodeString(UNZIP_SUCCESS_CONFIG);
                                    String downloadConfig = kv.decodeString(DOWNLOAD_SUCCESS_CONFIG);
                                    Log.e("downloadWorker", "unZipConfig = " + unZipConfig);
                                    Log.e("downloadWorker", "downloadConfig = " + downloadConfig);
                                    // 文件下载失败,旧文件不存在不能进入,旧文件存在进入解压程序
                                    Data isFailedData = workInfo.getOutputData();
                                    downloadedFailedMessage.postValue(isFailedData.getString(DOWNLOAD_FILE_EXCEPTION));
                                }
                                break;
                                default:
                                    break;
                            }
                        });
        downloadId = downloadWorker.getId();
    }

@Override
    protected void onCleared() {
        super.onCleared();
WorkManager.getInstance(ContextProvider.get().getContext()).cancelWorkById(unZipAssertId);
        WorkManager.getInstance(ContextProvider.get().getContext()).cancelWorkById(downloadId);
        WorkManager.getInstance(ContextProvider.get().getContext()).cancelWorkById(unZipId);
    }

3.注意事项

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,752评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,100评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,244评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,099评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,210评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,307评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,346评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,133评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,546评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,849评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,019评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,702评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,331评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,030评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,260评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,871评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,898评论 2 351

推荐阅读更多精彩内容