问权限的代码︰
private static final int REQUEST_PERMISSION_LOCATION = 255; // int should be between 0 and 255
// When you need the permission, e.g. onCreate, OnClick etc.
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSION_LOCATION);
} else {
// We have already permission to use the location
}
和结果︰
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// We now have permission to use the location
}
}
}
在 Android Manifest :