Android power optimization (3) - JobScheduler Merge task flow

JobScheduler Merge task flow

In the course of our development, we encounter such a scenario, such as uploading location information, personal information synchronization, synchronize contacts, these tasks do not require immediate treatment, we need to call in a particular scene, such as connection wifi, charging transfer. There is also a scene is recalled after a certain number of tasks

This time we can use to achieve JobScheduler merge workflow and executed at the right time

example

An example is provided here: https://github.com/ddssingsong/JobManager
Source Download: https://download.csdn.net/download/u011077027/11241799

Open a backstage Service kept calling location, location after successfully uploaded to the server, there needs to be more positioning and upload the results merged at the time of connection wifi

Start

public class JobManager {
    public static final String TAG = "dds_JobManager";
    private static JobManager instance;
    private JobScheduler jobScheduler;
    private Context context;

    private static final int jobId = 0; // 任务ID

    public static JobManager getInstance() {
        if (null == instance)
            instance = new JobManager();
        return instance;
    }

    public void init(Context context) {
        this.context = context.getApplicationContext();
        jobScheduler = (JobScheduler)
                context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

    }

    /**
     * 添加一个任务
     *
     * @param location 需要发送的内容
     */
    public void addJob(String location) {
        if (null == jobScheduler) {
            return;
        }
        JobInfo pendingJob = null;
        //整合多个job,7.0之上和之下不太一样
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            pendingJob = jobScheduler.getPendingJob(jobId);
        } else {
            List<JobInfo> allPendingJobs = jobScheduler.getAllPendingJobs();
            for (JobInfo info : allPendingJobs) {
                if (info.getId() == jobId) {
                    pendingJob = info;
                    break;
                }
            }
        }
        //找到待执行的job
        if (null != pendingJob) {
            //多个坐标信息拼到一起 上传
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //数据 与Intent 一样
                PersistableBundle extras = pendingJob.getExtras();
                //获得上一次设置的location数据
                String data = extras.getString("DATA");
                //比如 多条坐标数据用@隔开
                location = data + "@" + location;
                jobScheduler.cancel(jobId);
            }
        }
        PersistableBundle extras = new PersistableBundle();
        extras.putString("DATA", location);
        //创建一个job
        JobInfo jobInfo = new
                JobInfo.Builder(jobId,
                new ComponentName(context, MyJobService.class))
                //只在充电的时候
                .setRequiresCharging(true)
                //不是蜂窝网络
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setExtras(extras).build();

        //提交任务
        Log.e(TAG, "提交任务");
        jobScheduler.schedule(jobInfo);
    }

}
public class MyJobService extends JobService {

    public static final String TAG = "dds_MyJobService";

    @Override
    public boolean onStartJob(JobParameters params) {
        new MyAsyncTask(this).execute(params);
        return true;
    }

    //当系统接收到一个取消请求时
    @Override
    public boolean onStopJob(JobParameters params) {
        //如果onStartJob返回false,那么onStopJob不会被调用
        // 返回 true 则会重新计划这个job
        return false;
    }

    static class MyAsyncTask extends AsyncTask<JobParameters, Void, Void> {
        private JobParameters jobParameters;
        private WeakReference<MyJobService> myJobServiceWeakReference;

        public MyAsyncTask(MyJobService myJobService) {
            myJobServiceWeakReference = new WeakReference<>(myJobService);
        }

        @Override
        protected Void doInBackground(JobParameters[] objects) {
            jobParameters = objects[0];
            Log.i(TAG, jobParameters.getJobId() + " 任务开始执行......");
            PersistableBundle extras = jobParameters.getExtras();
            String location = extras.getString("DATA");
            Log.i(TAG, jobParameters.getJobId() + " 上传:" + location);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

         */
        @Override
        protected void onPostExecute(Void s) {
            //true表示需要重复执行
            //false反之
            myJobServiceWeakReference.get().jobFinished(jobParameters, false);
            Log.i(TAG, jobParameters.getJobId() + "任务执行完成......");
        }
    }

Guess you like

Origin blog.csdn.net/u011077027/article/details/91993234