2017-12-18 53 views
0

我在Service內使用FusedLocationProviderClient
我想以正確的方式「停止」它。如何正確停止FusedLocationProviderClient?

使用下面的代碼很好嗎?

@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()); 
    } 

回答

1

只是調用的onDestroy

removeLocationUpdates爲requestLocationUpdates,它說:

此調用將保持谷歌Play服務的連接活動,所以請確保在不再需要時調用removeLocationUpdates(LocationCallback),否則您失去了自動連接管理的好處。

0

只是改變onDestroy();這樣:

@Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     if(locationclient!=null) 
      locationclient.disconnect(); 
    }