jectpack系列之WorkManager

目录

0.WM介绍
1.实现原理
2.使用方式
3.自我思考

WorkManager介绍

背景

安卓开发应该都听过保活,不过随着安卓系统不同版本对电量的优化,对于之前的保活策略基本都不可用了,比如之前的1像素、粘性服务、服务销毁时启动、多个进程互相拉活、监听广播、设置前台服务优先级等。现在比较靠谱的方案:厂商白名单(比如我们现在的APP,微信) 或者是通过修改zygote底层实现,比如鹅厂的某APP启动了大概4个组,每组两个进程,两两互相拉起。

官方在安卓12推出的加急作业 通过 setExpedited()来修饰workmanager
image.png

WorkManager简介

作用

1.确保重要的后台任务,一定会被执行,后台任务(上传,下载,同步数据 等)
2.内部对电量进行了优化,可以管理后台任务,通常是是可延迟的后台任务
3.WorkManager不能做保活操作
4.一个小细节,如果你设置执行时间小于15分钟,会被推迟到15分钟才会下次调度

按官方介绍:WorkManager会选择一种合适的方式来安排后台任务 - 具体取决于设备API级别和包
含的依赖项,WorkManager可能会使用 JobScheduler,Firebase JobDispatcher或
AlarmManager

1.使用方式

角色介绍:
官方文档:https://developer.android.com/about/versions/12/foreground-services?hl=zh-cn
1.Worker:需要执行的具体任务,
2.WorkRequest:可以这样理解,执行一项单一的任务,执行会有具体ID,可以通过ID取消

1.初始化
WorkManager.getInstance(this) // 各种初始化的工作
2.加入队列
.enqueue(oneTimeWorkRequest2); // 加入队列,触发后台任务工作
3.约束条件执行

我们可以执行该任务执行的时机。如下满足网络连接上,并且不在低电量状态。

   // 约束条件
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED) // 约束条件,必须是网络连接
                .setRequiresBatteryNotLow(true)
                .build();

        // 构建Request
        OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MainWorker7.class)
                .setConstraints(constraints)
                .build();

        // 加入队列
        WorkManager.getInstance(this).enqueue(request);
2.执行具体任务如下
public class MainWorker extends Worker {

    public final static String TAG = MainWorker.class.getSimpleName();


    private Context mContext;
    private WorkerParameters workerParams;

    // 有构造函数
    public MainWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        this.mContext = context;
        this.workerParams = workerParams;
    }

    @SuppressLint("RestrictedApi")
    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "MainWorker7 doWork: 后台任务执行了 started");
        //TODO
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return Result.failure();  //执行任务失败
        }


        return new Result.Success(); // 本地执行 doWork 任务时 成功 执行任务完毕
    }


}
3.验证是否如官方说的 杀进程关机后重启也能执行

我们可以构造一个约束条件,只有在有网情况下执行,比如点击某个按钮,执行workmanager,在dowork中去创建一个名字叫测试的文件
我们先断开网络,点击,去查看是否生成,发现并没有生成。杀进程、关机后,恢复网络。进入APP,啥都不要做。再去查看,居然生成了文件。
你应该能想到他是怎么实现的,肯定是存储了,绝对不是存在内存的!!

源码分析

1.WorkManager.getInstance(this)

单例初始化了一个WorkManagerImpl对象,有个细节,这里我们调用不会走到if里面的逻辑,因为workmanager组件,也使用了contentprovider实现初始化

public static @NonNull WorkManagerImpl getInstance(@NonNull Context context) {
        synchronized (sLock) {
            WorkManagerImpl instance = getInstance();
            if (instance == null) {
                Context appContext = context.getApplicationContext();
                if (appContext instanceof Configuration.Provider) {
                    initialize(
                            appContext,
                            ((Configuration.Provider) appContext).getWorkManagerConfiguration());
                    instance = getInstance(appContext);
                } else {
                    throw new IllegalStateException("WorkManager is not initialized properly.  You "
                            + "have explicitly disabled WorkManagerInitializer in your manifest, "
                            + "have not manually called WorkManager#initialize at this point, and "
                            + "your Application does not implement Configuration.Provider.");
                }
            }

            return instance;
        }
    }

也就是在他的provider中,就会执行以下代码

 public boolean onCreate() {
        // Initialize WorkManager with the default configuration.
        WorkManager.initialize(getContext(), new Configuration.Builder().build());
        return true;
    }
image.png
2.workmanageImpl构造方法
    public WorkManagerImpl(
            @NonNull Context context,
            @NonNull Configuration configuration,
            @NonNull TaskExecutor workTaskExecutor,
            @NonNull WorkDatabase database) {
        Context applicationContext = context.getApplicationContext();
        Logger.setLogger(new Logger.LogcatLogger(configuration.getMinimumLoggingLevel()));
        List schedulers = createSchedulers(applicationContext, workTaskExecutor); //重点1
        Processor processor = new Processor(
                context,
                configuration,
                workTaskExecutor,
                database,
                schedulers);
        internalInit(context, configuration, workTaskExecutor, database, schedulers, processor); //重点2
    }
3.创建调度器

上面的重点1中创建一个调度的List集合,细节来了,Arrays,aslist这个不能增删,要么包装一层,要么用collections集合的方法。里面重点是创建一个贪吃的调度器

public List createSchedulers(
            @NonNull Context context,
            @NonNull TaskExecutor taskExecutor) {

        return Arrays.asList(
                Schedulers.createBestAvailableBackgroundScheduler(context, this),
                // Specify the task executor directly here as this happens before internalInit.
                // GreedyScheduler creates ConstraintTrackers and controllers eagerly.
                new GreedyScheduler(context, taskExecutor, this)); //创建一个贪吃的调度器
    }

里面构建了各种调度控制器,

    public WorkConstraintsTracker(
            @NonNull Context context,
            @NonNull TaskExecutor taskExecutor,
            @Nullable WorkConstraintsCallback callback) {

        Context appContext = context.getApplicationContext();
        mCallback = callback;
        mConstraintControllers = new ConstraintController[] {
                new BatteryChargingController(appContext, taskExecutor),
                new BatteryNotLowController(appContext, taskExecutor),
                new StorageNotLowController(appContext, taskExecutor),
                new NetworkConnectedController(appContext, taskExecutor),
                new NetworkUnmeteredController(appContext, taskExecutor),
                new NetworkNotRoamingController(appContext, taskExecutor),
                new NetworkMeteredController(appContext, taskExecutor)
        };
        mLock = new Object();
    }

同时,在WorkmanagerImpl的构造中还创建了Processor,然后调用internalInit方法

mWorkTaskExecutor.executeOnBackgroundThread(new ForceStopRunnable(context, this));

里面就是判断APP是否应该执行任务

public void run() {
        // Migrate the database to the no-backup directory if necessary.
        WorkDatabasePathHelper.migrateDatabase(mContext);
        // Clean invalid jobs attributed to WorkManager, and Workers that might have been
        // interrupted because the application crashed (RUNNING state).
        Logger.get().debug(TAG, "Performing cleanup operations.");
        try {
            boolean needsScheduling = cleanUp();
            if (shouldRescheduleWorkers()) {
                Logger.get().debug(TAG, "Rescheduling Workers.");
                mWorkManager.rescheduleEligibleWork();
                // Mark the jobs as migrated.
                mWorkManager.getPreferenceUtils().setNeedsReschedule(false);
            } else if (isForceStopped()) {
                Logger.get().debug(TAG, "Application was force-stopped, rescheduling.");
                mWorkManager.rescheduleEligibleWork();
            } else if (needsScheduling) {
                Logger.get().debug(TAG, "Found unfinished work, scheduling it.");
                Schedulers.schedule(
                        mWorkManager.getConfiguration(),
                        mWorkManager.getWorkDatabase(),
                        mWorkManager.getSchedulers());
            }
            mWorkManager.onForceStopRunnableCompleted();
        } catch (SQLiteCantOpenDatabaseException
                | SQLiteDatabaseCorruptException
                | SQLiteAccessPermException exception) {
            // ForceStopRunnable is usually the first thing that accesses a database (or an app's
            // internal data directory). This means that weird PackageManager bugs are attributed
            // to ForceStopRunnable, which is unfortunate. This gives the developer a better error
            // message.
            String message =
                    "The file system on the device is in a bad state. WorkManager cannot access "
                            + "the app's internal data store.";
            Logger.get().error(TAG, message, exception);
            throw new IllegalStateException(message, exception);
        }
    }
4.再执行enqueue(request)方法

里面调用new WorkContinuationImpl(this, workRequests).enqueue(); 然后执行一个runnable,

public @NonNull Operation enqueue() {
        // Only enqueue if not already enqueued.
        if (!mEnqueued) {
            // The runnable walks the hierarchy of the continuations
            // and marks them enqueued using the markEnqueued() method, parent first.
            EnqueueRunnable runnable = new EnqueueRunnable(this);
            mWorkManagerImpl.getWorkTaskExecutor().executeOnBackgroundThread(runnable);
            mOperation = runnable.getOperation();
        } else {
            Logger.get().warning(TAG,
                    String.format("Already enqueued work ids (%s)", TextUtils.join(", ", mIds)));
        }
        return mOperation;
    }
5.异步任务执行

里面有两个比较重要的逻辑。首先是处理了数据库相关的,这里就是存储的位置。

 public EnqueueRunnable(@NonNull WorkContinuationImpl workContinuation) {
        mWorkContinuation = workContinuation;
        mOperation = new OperationImpl();
    }

    @Override
    public void run() {
        try {
            if (mWorkContinuation.hasCycles()) {
                throw new IllegalStateException(
                        String.format("WorkContinuation has cycles (%s)", mWorkContinuation));
            }
            boolean needsScheduling = addToDatabase();
            if (needsScheduling) {
                // Enable RescheduleReceiver, only when there are Worker's that need scheduling.
                final Context context =
                        mWorkContinuation.getWorkManagerImpl().getApplicationContext();
                PackageManagerHelper.setComponentEnabled(context, RescheduleReceiver.class, true);
                scheduleWorkInBackground();
            }
            mOperation.setState(Operation.SUCCESS);
        } catch (Throwable exception) {
            mOperation.setState(new Operation.State.FAILURE(exception));
        }
    }

可以看到还是比较严谨,开启事物处理数据库逻辑。

    public boolean addToDatabase() {
        WorkManagerImpl workManagerImpl = mWorkContinuation.getWorkManagerImpl();
        WorkDatabase workDatabase = workManagerImpl.getWorkDatabase();
        workDatabase.beginTransaction();
        try {
            boolean needsScheduling = processContinuation(mWorkContinuation);
            workDatabase.setTransactionSuccessful();
            return needsScheduling;
        } finally {
            workDatabase.endTransaction();
        }
    }
6.会执行调度的方法,schedule
public static void schedule(
            @NonNull Configuration configuration,
            @NonNull WorkDatabase workDatabase,
            List schedulers) {
        if (schedulers == null || schedulers.size() == 0) {
            return;
        }

        WorkSpecDao workSpecDao = workDatabase.workSpecDao();
        List eligibleWorkSpecs;

        workDatabase.beginTransaction();
        try {
            eligibleWorkSpecs = workSpecDao.getEligibleWorkForScheduling(
                    configuration.getMaxSchedulerLimit());
            if (eligibleWorkSpecs != null && eligibleWorkSpecs.size() > 0) {
                long now = System.currentTimeMillis();

                // Mark all the WorkSpecs as scheduled.
                // Calls to Scheduler#schedule() could potentially result in more schedules
                // on a separate thread. Therefore, this needs to be done first.
                for (WorkSpec workSpec : eligibleWorkSpecs) {
                    workSpecDao.markWorkSpecScheduled(workSpec.id, now);
                }
            }
            workDatabase.setTransactionSuccessful();
        } finally {
            workDatabase.endTransaction();
        }

        if (eligibleWorkSpecs != null && eligibleWorkSpecs.size() > 0) {
            WorkSpec[] eligibleWorkSpecsArray = eligibleWorkSpecs.toArray(new WorkSpec[0]);
            // Delegate to the underlying scheduler.
            for (Scheduler scheduler : schedulers) {
                scheduler.schedule(eligibleWorkSpecsArray);
            }
        }
    }

里面同样是开启事物从数据库中取

7.贪吃调度器的调度

里面就处理了约束相关逻辑


8. mWorkManagerImpl.startWork(workSpec.id);

无约束的直接启动 mWorkManagerImpl.startWork(workSpec.id);,

public boolean startWork(
            @NonNull String id,
            @Nullable WorkerParameters.RuntimeExtras runtimeExtras) {

        WorkerWrapper workWrapper;
        synchronized (mLock) {
            // Work may get triggered multiple times if they have passing constraints
            // and new work with those constraints are added.
            if (mEnqueuedWorkMap.containsKey(id)) {
                Logger.get().debug(
                        TAG,
                        String.format("Work %s is already enqueued for processing", id));
                return false;
            }

            workWrapper =
                    new WorkerWrapper.Builder(
                            mAppContext,
                            mConfiguration,
                            mWorkTaskExecutor,
                            this,
                            mWorkDatabase,
                            id)
                            .withSchedulers(mSchedulers)
                            .withRuntimeExtras(runtimeExtras)
                            .build();
            ListenableFuture future = workWrapper.getFuture();
            future.addListener(
                    new FutureListener(this, id, future),
                    mWorkTaskExecutor.getMainThreadExecutor());
            mEnqueuedWorkMap.put(id, workWrapper);
        }
        mWorkTaskExecutor.getBackgroundExecutor().execute(workWrapper);
        Logger.get().debug(TAG, String.format("%s: processing %s", getClass().getSimpleName(), id));
        return true;
    }
最后调到我们自己的doWork方法
 @Override
    public final @NonNull ListenableFuture startWork() {
        mFuture = SettableFuture.create();
        getBackgroundExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Result result = doWork();
                    mFuture.set(result);
                } catch (Throwable throwable) {
                    mFuture.setException(throwable);
                }

            }
        });
        return mFuture;
    }
有条件约束的逻辑

代码太多,就不贴了,大概说下流程,比如网络限制的,是通过连网的广播,开启SystemAlarmService,切换action,然后还是调用没有约束的逻辑执行。

你可能感兴趣的:(jectpack系列之WorkManager)