JobService and JobIntentService

Table of contents

1. JobService

1. Create JobService subclass

2. Manifest file registration JobService

3. Scheduling jobs-starting JobService

(1) Prepare JobInfo (job information)

(2) Get JobScheduler (job scheduling)

(3) JobScheduler schedules JobInfo

二、 JobIntentService

1. Create a JobIntentService subclass

2. Manifest file registration JobIntentService

3. Start JobIntentService

3. Front desk service


JobService and JobIntentSerice werecreated to continue execution under specified circumstances << after the program is closed .

The relationship between JobService and JobIntentService is similar to the relationship between Service and IntentService. JobService runs in the main thread , and JobIntentService will prepare a child thread for each startup and run in it .

Service and InentService will be terminated when the App is shut down, while JobService and IntentService will continue to run after the App is shut down.

  • JobService: Available for Android 5.0 (API level 21) and higher. onStartJob() is executed asynchronously, and you need to call the jobFinished() method to notify the system when the job is completed . This enables you to perform long-running tasks in a background thread.
  • JobIntentService: Provides backward compatibility before Android 8.0 (API level 26), allowing you to use the JobScheduler (job scheduling) function on older devices. The onHandleWork() method is executed in an independent worker thread and will automatically stop the service after all tasks are completed. There is no need to manually call stopSelf() or stopSelfResult() .

1. JobService

1. Create JobService subclass

Create a subclass that inherits the JobService class and implement the onStartJob() method and onStopJob() method.

Rewrite the background task logic in the onStartJob() method . This method returns true to indicate that the job is executed here, and returns false to indicate that the job execution is completed.

Rewrite the job cancellation logic in the onStopJob() method . This method returns true to indicate that you want the job to be rescheduled, and returns false to indicate that the job does not need to be executed again.

If you want to abort the task, you can use the JobFinished(JobParameters jp, boolean b) method and return false in onStartJob() . The first parameter of this method is the parameter of the current job (used to tell the system which job has ended), and the second parameter is Whether to reschedule the job.

public class MyJobService extends JobService {
    @Override
    public boolean onStartJob(JobParameters params) {
        // 在这里执行后台任务逻辑

        // 返回 true 表示作业在这里执行,返回 false 表示作业已经执行完毕
        return true;

        // 停止JobService可使用 jobFinished(params, false)并返回false
        // jobFinished(params, false);
        // return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        // 在这里处理作业被取消的逻辑

        // 返回 true 表示希望作业被重新调度
        return false;
    }
}

2. Manifest file registration JobService

Please note that you must include android:permission="android.permission.BIND_JOB_SERVICE" .

<application
        ... ... >
        ... ...

        <service android:name=".MyJobService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="false"/>

</application>

3. Scheduling jobs-starting JobService

(1) Prepare JobInfo (job information)

Created using JobInfo.Builder, where you can set network conditions, charging conditions, job execution period (in milliseconds), and automatically reschedule jobs after device restart.

(2) Get JobScheduler (job scheduling)

Use getSystemService(JOB_SCHEDULER_SERVICE) to get the JobSecheduler.

(3) JobScheduler schedules JobInfo

Use the schedule() method to schedule JobInfo and start JobService.

JobInfo jobInfo = new JobInfo.Builder(JOB_ID, new ComponentName(this, MyJobService.class))
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)  // 设置网络条件
        .setRequiresCharging(true)  // 设置充电条件
        .setPeriodic(15 * 60 * 1000)  // 设置作业的周期性执行,单位是毫秒
        //.setPersisted(true)  // 设备重启,作业重新调度
        //.setRequiresDeviceIdle(true)  //设置作业是否需要设备处于空闲状态才能执行
        //.setMinimumLatency(0)  //设置作业的最小延迟时间,即作业在何时可以开始执行(毫秒)
        //.setOverrideDeadline(5000)  //设置作业的截止时间,即作业在何时必须开始执行(毫秒)
        .build();

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfo);

二、 JobIntentService

1. Create a JobIntentService subclass

public class MyJobIntentService extends JobIntentService {

    protected void onHandleWork(@NonNull Intent intent) {
        // 执行任务代码
    }

    public static void enqueueWork(Context context, Intent work) {
        // 该方法为自行创建
        // 通过这个静态方法来 enqueue (入队) 任务
        enqueueWork(context, MyJobIntentService.class, 2333 , work);
    }

}

2. Manifest file registration JobIntentService

Please note that you must include android:permission="android.permission.BIND_JOB_SERVICE" .

<application
        ... ... >
        ... ...

        <service android:name=".MyJobIntentService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="false"/>

</application>

3. Start JobIntentService

Use the enqueueWork() method to start the JobIntentService.

Intent may or may not have additional information.

//Intent
Intent intent=new Intent(MainActivity.this,MyJobIntentService.class);
//附加信息(可不添加)
//intent.putExtra("key", value);
//启动服务(调用自定义静态方法)
MyJobIntentService.enqueueWork(MainActivity.this,intent);

3. Front desk service

JobService is the same as JobIntentService and Service is the same as IntentService. You can use startForeground() to start the foreground (display notifications) and stopForeground() to stop the foreground (delete notifications).

tag: JobService, JobIntentService, job, JobScheduler, worker, WorkManager, background service, background, service, service

Guess you like

Origin blog.csdn.net/m0_57150356/article/details/135043380