背景:
Android系统8.0及以上,开启Service必须使用startForegroundService(Intent intent)方法,对应的Service则必须设置startForeground(int id, Notification notification),因而我们必须创建一个通知,这样在服务运行当中,会一直显示一条“xx正在运行”类似的通知。
目标:
消除“xx正在运行”的通知内容
解决方案:
使用官方提供的JobService,通过JobInfo.Builder创建对应需求的JobInfo,通过JobScheduler.schedule(JobInfo jobInfo)实现Service功能
- Android5.0推出JobService,因此系统5.0及以后版本可以使用。
- Android7.0版本以下可以使用JobInfo.Builder.setPeriodic(long intervalMillis)自由设置任务执行间隔时间。
- Android7.0及以后系统版本的任务执行最小间隔限定为JobInfo.getMinPeriodMillis(),也就是15分钟。但是setPeriodic(long intervalMillis, long flexMillis)的第二个参数可以设置下次任务执行的窗口时间,时间为JobInfo.getMinFlexMillis()(5分钟)或者任务间隔时间的5%,这两个值谁大取谁。具体任务执行如下图
代码示例:
JobService示例
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Build;
import android.support.annotation.RequiresApi;
/**
* created by z on 2018/11/19
* 系统5.0以上使用的服务
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CowboyJobService extends JobService {
@Override
public boolean onStartJob(JobParameters jobParameters) {
//此处进行自定义的任务
return false;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
}
AndroidManifest.xml的<application></application>标签内声明该JobService
//具体的JobService名字和路径以自己编写的为准
<service
android:name=".service.CowboyJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
开启运行JobService
//开启JobService服务:CowboyJobService.class为上边创建的JobService
public static void startPollingService(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(context, CowboyJobService.class));
builder.setMinimumLatency(0)
.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setPeriodic(JobInfo.getMinPeriodMillis(), JobInfo.getMinFlexMillis());
} else {
builder.setPeriodic(TimeUnit.MINUTES.toMillis(5));
}
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(builder.build());
}
} else {
//系统5.0以下的可继续使用Service
}
}