background:
For Android system 8.0 and above, the startForegroundService(Intent intent) method must be used to start the Service , and the corresponding Service must be set to startForeground(int id, Notification notification) , so we must create a notification so that when the service is running, it will always display a " xx is running" similar notice.
aims:
Eliminate "xx is running" notification content
solution:
Use of official JobService , by JobInfo.Builder creates a corresponding demand JobInfo , by JobScheduler.schedule (JobInfo jobInfo) to implement Service function
- Android5.0 launches JobService, so system 5.0 and later versions can be used.
- Below Android7.0 version, you can use JobInfo.Builder.setPeriodic(long intervalMillis) to freely set the task execution interval.
- The minimum interval for task execution of Android7.0 and later system versions is limited to JobInfo.getMinPeriodMillis() , which is 15 minutes . But the second parameter of setPeriodic (long intervalMillis, long flexMillis) can set the window time for the next task execution, the time is JobInfo.getMinFlexMillis() (5 minutes) or 5% of the task interval time , whichever is greater Who. The specific task execution is as follows
Code example:
JobService example
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;
}
}
The JobService is declared in the <application></application> tag of AndroidManifest.xml
//具体的JobService名字和路径以自己编写的为准
<service
android:name=".service.CowboyJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
Start running 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
}
}