沈阳开发网站公司哪家好,网页设计软件官网模板网站,包装设计是什么,大连建设网官网网上办公大厅JobService是Android L时候官方新增的组件#xff0c;适用于需要特定条件才执行后台任务的场景。由系统统一管理和调度#xff0c;在特定场景下使用JobService更加灵活和省心#xff0c;相当于是Service的加强或者优化。 JobService是JobScheduler的回调#xff0c;是安排的… JobService是Android L时候官方新增的组件适用于需要特定条件才执行后台任务的场景。由系统统一管理和调度在特定场景下使用JobService更加灵活和省心相当于是Service的加强或者优化。 JobService是JobScheduler的回调是安排的Job请求的实际处理类。需要我们覆写onStartJob (JobParameters)方法并在里面实现实际的任务逻辑。因为JobService的执行是在APP的主线程里响应的所以必须提供额外的异步逻辑去执行这些任务。 代码如下
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;public class MyJobService extends JobService {private static final int JOB_ID 1;private static final long INTERVAL_MILLIS 10 * 1000; // 10 secondsOverridepublic boolean onStartJob(JobParameters params) {// 在这里执行你的后台任务System.out.println(Job started);scheduleJob(getApplicationContext()); // 重新调度作业return false;}Overridepublic boolean onStopJob(JobParameters params) {// 在这里取消你的后台任务System.out.println(Job stopped);return false;}public static void scheduleJob(Context context) {if (Build.VERSION.SDK_INT Build.VERSION_CODES.N) {JobScheduler jobScheduler (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);ComponentName componentName new ComponentName(context, MyJobService.class);JobInfo jobInfo new JobInfo.Builder(JOB_ID, componentName).setMinimumLatency(INTERVAL_MILLIS).setOverrideDeadline(INTERVAL_MILLIS).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();jobScheduler.schedule(jobInfo);} else {// 在 Android N 以下版本使用 AlarmManager 实现定时任务Intent intent new Intent(context, MyJobService.class);PendingIntent pendingIntent PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);AlarmManager alarmManager (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() 1000, pendingIntent);}}
}
在activity里面调用
MyJobService.scheduleJob(this)