• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

如何正确停止FusedLocationProviderClient?

java 来源:Academy of Programmer 3次浏览

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

===========解决方案如下:

只是调用的onDestroy

removeLocationUpdates为requestLocationUpdates,它说:

此调用将保持谷歌Play服务的连接活动,所以请确保在不再需要时调用removeLocationUpdates(LocationCallback),否则您失去了自动连接管理的好处。


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)