从 Android 6.0(API 级别 23)开始,用户在应用运行时授予应用权限,而不是在安装应用时。
首先实现ActivityCompat.OnRequestPermissionsResultCallback
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if ( ActivityCompat.checkSelfPermission( this, ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) {
}
}
}
}
然后检查是否需要运行时权限
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
if ( ActivityCompat.checkSelfPermission( this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
//Location Permission already granted
map.setMyLocationEnabled( true );
} else {
//Request Location Permission
requestLocationPermission();
}
}
private void requestLocationPermission() {
if ( ContextCompat.checkSelfPermission( this, ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
// Should we show an explanation?
if ( ActivityCompat.shouldShowRequestPermissionRationale( this, ACCESS_FINE_LOCATION ) ) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions( MainActivity.this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions( this, new String[]{ACCESS_FINE_LOCATION}, REQUEST_LOCATION );
}
}
}
有关运行时权限的更多信息:Requesting Permissions at Run Time