位置服务没有从奥利奥调用

时间:2018-05-30 08:11:16

标签: android performance android-location android-8.0-oreo android-jobscheduler

我使用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
  }

1 个答案:

答案 0 :(得分:3)

此问题与以下代码有关:

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

从Android N开始,JobScheduler的最短周期为15分钟。 5秒的频率太频繁且不合适。