2016-12-02 69 views
-2

我使用下面的代碼檢查,並要求允許對GPS:如何在棒棒糖中授予ACCESS_FINE_LOCATION權限?

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

    ActivityCompat.requestPermissions(this, new String[]{ 
       Manifest.permission.ACCESS_FINE_LOCATION }, 1); 
} 

我已經在清單如下:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 

我部署應用程序到Android 5.0 .2使用Android Studio的平板電腦。

我知道checkSelfPermission不會返回PERMISSION_GRANTED並且它執行requestPermissions,但它不顯示對話框或授予權限。我如何授予應用程序使用GPS的權限?

+1

「我知道'checkSelfPermission'不會返回'PERMISSION_GRANTED'」 - 你確定你有清單中正確位置的權限嗎?即,''標籤之外? –

+0

[如何在Android中以編程方式獲取當前GPS位置?](http://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in -android) – Gattsu

回答

0

您可以使用下面的代碼。使用下面的代碼,它會要求打開GPS。

public class Activity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, LocationListener { 


    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; 

    private Location mLastLocation; 

    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 

    // boolean flag to toggle periodic location updates 
    private boolean mRequestingLocationUpdates = false; 

    private LocationRequest mLocationRequest; 

    // Location updates intervals in sec 
    private static int UPDATE_INTERVAL = 600000; // 10 min 
    private static int FATEST_INTERVAL = 600000; // 10 min 
    private static int DISPLACEMENT = 5; // 5 meters 

    PendingResult<LocationSettingsResult> result; 

    AlertDialog.Builder alertDialogBuilder; 
    LinearLayout parent; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 


     alertDialogBuilder = new AlertDialog.Builder(Activity.this); 

     parent = new LinearLayout(ActivitySetting.this); 
     parent.setGravity(Gravity.CENTER); 
     parent.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 
       ViewGroup.LayoutParams.MATCH_PARENT)); 


     alertDialogBuilder.setTitle("name"); 

     // First we need to check availability of play services 
     if (checkPlayServices()) { 

      // Building the GoogleApi client 
      buildGoogleApiClient(); 

      createLocationRequest(); 
     } 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)); 


     result = 
       LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

     result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
      @Override 
      public void onResult(LocationSettingsResult result) { 
       final Status status = result.getStatus(); 
       final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates(); 
       // final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates(); 
       switch (status.getStatusCode()) { 
        case LocationSettingsStatusCodes.SUCCESS: 

         break; 
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 

         alertDialogBuilder.setMessage("Turn On GPS"); 
         alertDialogBuilder.setView(parent); 
         alertDialogBuilder.setCancelable(false); 

         alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           try { 
            // Show the dialog by calling startResolutionForResult(), 
            // and check the result in onActivityResult(). 
            status.startResolutionForResult(ActivitySetting.this, 1000); 
           } catch (IntentSender.SendIntentException e) { 
            // check error. 
           } 

          } 
         }); 

         alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           try { 
            // Show the dialog by calling startResolutionForResult(), 
            finish(); 
           } catch (Exception e) { 
            // check error. 
           } 

          } 
         }); 
         alertDialogBuilder.create(); 
         alertDialogBuilder.show(); 
         break; 
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 

         // you can do here what ever you want. 

         break; 
       } 
      } 
     }); 

    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.connect(); 
     } 
    } 


    @Override 
    protected void onResume() { 
     super.onResume(); 

     checkPlayServices(); 

     // Resuming the periodic location updates 
     if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
      startLocationUpdates(); 
     } 
    } 

    /** 
    * Creating google api client object 
    */ 
    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API).build(); 
    } 


    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); 
     switch (requestCode) { 
      case 1000: 
       switch (resultCode) { 
        case Activity.RESULT_OK: 

         // If user has active gps you will get it here 

         break; 
        case Activity.RESULT_CANCELED: 
         // The user was asked to change settings, but chose not to turn on 

         break; 
        default: 

         break; 
       } 
       break; 
     } 
    } 

    /** 
    * Method to verify google play services on the device 
    */ 
    private boolean checkPlayServices() { 
     int resultCode = GooglePlayServicesUtil 
       .isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
       GooglePlayServicesUtil.getErrorDialog(resultCode, this, 
         PLAY_SERVICES_RESOLUTION_REQUEST).show(); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "This device is not supported.", Toast.LENGTH_LONG) 
         .show(); 
       finish(); 
      } 
      return false; 
     } 
     return true; 
    } 


    /** 
    * Google api callback methods 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     Log.i("fsAil", "Connection failed: ConnectionResult.getErrorCode() = " 
       + result.getErrorCode()); 
    } 

    @Override 
    public void onConnected(Bundle arg0) { 

    } 

    @Override 
    public void onConnectionSuspended(int arg0) { 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 


    } 

} 

這裏API <= 21 GPS權限將被自動授予(如果你定義的清單權限),並且棉花糖及以上你需要問的運行許可(也是在清單中添加的權限),但permission granted之後纔開啓GPS你可以使用上面的代碼。

有了這段代碼,一個警告框會出現,並要求打開GPS(如果沒有激活)。所以你可以直接用上面的代碼打開GPS。

希望這對你有所幫助。

乾杯!

+0

如果問題重複,將它們標記爲**重複** – Gattsu

+0

好的。當然。會記住這一點。謝謝。 –

+0

'爲requestpermission'寫代碼?如果您給出答案,請完整填寫以幫助OP和未來的讀者繼續獲得完整和準確的答案 – Gattsu

1
ActivityCompat.requestPermissions(this, new String[]{ 
       Manifest.permission.ACCESS_FINE_LOCATION }, 1); 

此代碼請求上的Android下英鎊... ... 4.to版本運行時權限我啓動的設置目的爲用戶打開優選如下設定(代替上述代碼的)

Intent myIntent = new Intent(Settings.ACTION_SETTINGS); 
         startActivity(myIntent); 
1

在清單中添加這些行:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

這些太:

<!-- Below permissions are used to detect required hardware or service providers for the application --> 
    <uses-feature 
     android:name="android.hardware.location" 
     android:required="true" /> 
    <uses-feature 
     android:name="android.hardware.location.gps" 
     android:required="true" />