我试图根据互联网连接(蜂窝)执行后台任务,所以我在jobinfo中设置了RequiredNetworkType(JobInfo.NETWORK_TYPE_CELLULAR),我期望后台作业服务在蜂窝互联网连接打开之前不会运行,但是即使关闭Internet连接,服务也会运行。
这是我的代码(jobinfo)
ComponentName componentName=new ComponentName(this,MyService.class);
JobInfo info=new JobInfo.Builder(0,componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_CELLULAR)
.setPersisted(true)
.setPeriodic(15000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultcode=scheduler.schedule(info);
if (resultcode==JobScheduler.RESULT_SUCCESS){
Log.d(TAG,"job scheduled");
}else{
Log.d(TAG,"failed");
}
我的工作服务
private static final String TAG="MyService";
boolean jobcancelled=false;
@Override
public boolean onStartJob(JobParameters params) {
backgroundService(params);
return true;
}
private void backgroundService(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
if (jobcancelled) {
return;
}
Notification.Builder notification = new Notification.Builder(MyService.this)
// this Builder class is deprecated
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setPriority(Notification.PRIORITY_MAX)
.setLights(0xff00ff00, 300, 100)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("My notification")
.setContentText("Hello Peter");
NotificationManagerCompat manager = NotificationManagerCompat.from(MyService.this);
manager.notify(1, notification.build());
jobFinished(params,false);
}
}).start();
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG,"job cancelled before completion");
jobcancelled=true;
return true;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。