2017-12-18 2 views
0

Ich verwende FusedLocationProviderClient innerhalb einer Service.
Ich möchte es auf eine richtige Weise "stoppen".Wie ordne ich FusedLocationProviderClient richtig an?

Ist es gut, den folgenden Code zu verwenden?

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

Und der Rest Code

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

Antwort

1

nur removeLocationUpdates in onDestroy nennen

für requestLocationUpdates, heißt es:

Dieser Aufruf der Google-Services-Verbindung aktiv Spielen halten, Stellen Sie also sicher, dass removeLocationUpdates (LocationCallback) aufgerufen wird, wenn Sie es sonst nicht mehr benötigen Sie verlieren die Vorteile des automatischen Verbindungsmanagements.

0

nur onDestroy(); Um dies zu ändern:

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