com.android.support:support-v4:23.0.1
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
GoogleApiClient
@Override public void onConnectionFailed(ConnectionResult result) { if (mResolvingError) { // Already attempting to resolve an error. return; } else if (result.hasResolution()) { try { mResolvingError = true; result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); } catch (SendIntentException e) { // There was an error with the resolution intent. Try again. mGoogleApiClient.connect(); } } else { // Show dialog using GooglePlayServicesUtil.getErrorDialog() showErrorDialog(result.getErrorCode()); mResolvingError = true; } }
ActivityCompat
Fragment
ContextCompat
checkSelfPermission
requestPermissions
private static final int REQUEST_CODE_LOCATION = 2; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Request missing location permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION); } else { // Location permission has been granted, continue as usual. Location myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); }
onRequestPermissionsResult
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_CODE_LOCATION) { if(grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // success! Location myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); } else { // Permission was denied or request was cancelled } }
shouldShowRequestPermissionRationale
private static final int REQUEST_CODE_LOCATION = 2; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION); } } else { // permission has been granted, continue as usual Location myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); }