我使用LocationService命令启动startService(),但是由于我了解到当应用程序在后台运行时,Oreo不会提供这项服务,因此我切换到了JobSchedular

我在lollipop中测试了该应用程序,并且JobSchedular正常工作,但是在Oreo中,它无法运行LocationService

我将break point放在LocationService的onCreate()方法中,只是没有去那里。

这就是我在做什么。

主要活动

它执行以下代码,但不响应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
  }

最佳答案

此问题与以下代码有关:

JobInfo.Builder builder= new JobInfo.Builder(11, componentName);
builder.setPeriodic(5000);


从Android N开始,JobScheduler至少需要15分钟。 5秒的频率太频繁,是不合适的。

10-08 07:50