如何正确停止FusedLocationProviderClient?

问题描述 投票:0回答:2

我在FusedLocationProviderClient中使用Service。 我想以正确的方式“停止”它。

使用以下代码是否好?

 @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop Looper of FusedLocationProviderClient  
        if (locationClient != null) {
            locationClient = null;
        }
    }

其余的代码

FusedLocationProviderClient locationClient;


protected void startLocationUpdates() {


        // Create the location request to start receiving updates
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        // Create LocationSettingsRequest object using location request
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        LocationSettingsRequest locationSettingsRequest = builder.build();

        // Check whether location settings are satisfied
        // https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
        SettingsClient settingsClient = LocationServices.getSettingsClient(this);
        settingsClient.checkLocationSettings(locationSettingsRequest);

        // new Google API SDK v11 uses getFusedLocationProviderClient(this)
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

        locationClient = getFusedLocationProviderClient(this);getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        // do work here
                        onLocationChanged(locationResult.getLastLocation());
                    }
                }, Looper.myLooper());
    }
java android fusedlocationproviderclient
2个回答
2
投票

只需在onDestroy中调用removeLocationUpdates

对于requestLocationUpdates,它说:

此调用将保持Google Play服务连接处于活动状态,因此请确保在不再需要时调用removeLocationUpdates(LocationCallback),否则您将失去自动连接管理的优势。


0
投票

只需将onDestroy();更改为:

@Override
    protected void onDestroy() {
        super.onDestroy();
        if(locationclient!=null)
            locationclient.disconnect();
    }
© www.soinside.com 2019 - 2024. All rights reserved.