2014-01-17 47 views

回答

6

我想我遲到回答這個問題。但沒關係。因此,通過新的API LocationSettingsRequest,我們只需點擊一下即可在應用內啓用位置。 所以這樣做;初始化GoogleApiClient

 GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this).build(); 
     mGoogleApiClient.connect(); 

,然後進行初始化爲低於LocationRequest:

LocationRequest mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(Util.UPDATE_INTERVAL_IN_MILLISECONDS); 
     mLocationRequest.setFastestInterval(Util.FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
    } 

現在通過LocationSettingsRequest使位置設置請求。

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 

     //************************** 
     builder.setAlwaysShow(true); //this is the key ingredient 
     //************************** 

     PendingResult<LocationSettingsResult> result = 
       LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 
     result.setResultCallback(locationSettingsResultCallback); 

所以,只要您撥打一個LocationSettingsRequest,它會彈出如下對話框:

enter image description here

所以處理任何選項,用戶選擇,則必須實現回調函數來處理每個選項象下面這樣:

ResultCallback<LocationSettingsResult> locationSettingsResultCallback = new ResultCallback<LocationSettingsResult>() { 
     @Override 
     public void onResult(LocationSettingsResult result) { 
      final Status status = result.getStatus(); 
      final LocationSettingsStates state = result.getLocationSettingsStates(); 
      switch (status.getStatusCode()) { 
       case LocationSettingsStatusCodes.SUCCESS: 
        // All location settings are satisfied. The client can initialize location 
        // requests here. 
        //startLocationUpdates(); 


        break; 
       case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
        // Location settings are not satisfied. But could be fixed by showing the user 
        // a dialog. 
        try { 
         // Show the dialog by calling startResolutionForResult(), 
         // and check the result in onActivityResult(). 
         status.startResolutionForResult(
           PickupLocationActivity.this, 1000); 
        } catch (IntentSender.SendIntentException e) { 
         // Ignore the error. 
        } 
        break; 
       case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
        // Location settings are not satisfied. However, we have no way to fix the 
        // settings so we won't show the dialog. 
        break; 
      } 
     } 
    }; 

參考:https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi

相關問題