多个requestLocationUpdates正在运行

时间:2018-08-18 10:47:01

标签: android location android-service android-fusedlocation

我使用熔融定位API请求位置更新。由于某种原因,我在后台服务中启动requestLocationUpdates。据我所知,系统中只有任何android服务的一个实例。但是,每次我使用startService()调用此服务时,都会创建一个新的位置侦听器,因此多个位置更新会并行工作。在创建新的 mLocationRequest 之前,我该如何检查?

public class LocationService extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

    //Service parameters
    final Context context = this;
    boolean isWorking = false;
    boolean jobCancelled = false;
    public boolean mustStop=false;
    GoogleApiClient mLocationClient;
    LocationRequest mLocationRequest = new LocationRequest();
    public String CurrentLocation = null;
  //Service methods
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LocationStartPoint();
        return START_STICKY;
     }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //Location API
    public void LocationStartPoint(){
        mLocationClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

        mLocationRequest.setInterval(30000);
        mLocationRequest.setFastestInterval(20000);
        int priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        mLocationRequest.setPriority(priority);
        mLocationClient.connect();
    }

    @Override
    public void onConnected(Bundle dataBundle) {

        if (Build.VERSION.SDK_INT < 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }
        else {
            LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
        }

    }

//other methods are out of context of this question

}

这就是我使用此服务的方式,用户可以通过单击“开始”按钮尝试多次运行该服务:

Intent startIntent=new Intent(this, LocationService.class);
startService(startIntent);

0 个答案:

没有答案