我使用LocationService
命令启动startService()
,但由于我了解到当应用处于后台时奥利奥不会接受此服务,我切换到JobSchedular
,
我在lollipop
测试了该应用,JobSchedular
工作得很好,但在奥利奥,它没有运行LocationService
我将break point
放在LocationService的onCreate()
方法中,它就不会去那里。
这就是我在做的事。
MainActivity
执行以下代码,但不对LocationUpdateService.class
public void initLocationJob(){
JobInfo jobInfo;
JobScheduler jobScheduler;
ComponentName componentName= new ComponentName(this, LocationUpdateService.class);
JobInfo.Builder builder= new JobInfo.Builder(11, componentName);
builder.setPeriodic(5000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setPersisted(true);
jobInfo= builder.build();
jobScheduler= (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfo);
}
LocationUpdateService
public class LocationUpdateService extends JobService implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
IServiceResponse {
@Override
public void onCreate() {
super.onCreate();
if (isGooglePlayServicesAvailable()) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartCommand: ");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(BACKGROUND_INTERVAL);
mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
this.params= params;
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d("JobStopped", "JobStopped");
return true;
}
@Override
public void onLocationChanged(Location location) {
//Get current Lat/lng and send it to server
}
答案 0 :(得分:3)
此问题与以下代码有关:
JobInfo.Builder builder= new JobInfo.Builder(11, componentName);
builder.setPeriodic(5000);
从Android N开始,JobScheduler的最短周期为15分钟。 5秒的频率太频繁且不合适。