下面列出了android.support.v4.app.ActivityCompat#shouldShowRequestPermissionRationale ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void startQrCode() {
// 申请相机权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// 申请权限
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
.CAMERA)) {
Toast.makeText(this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
return;
}
// 申请文件读写权限(部分朋友遇到相册选图需要读写权限的情况,这里一并写一下)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 申请权限
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
return;
}
// 二维码扫码
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent, Constant.REQ_QR_CODE);
}
public static void requestCameraPermission(Activity activity, boolean requestWritePermission) {
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.CAMERA) || (requestWritePermission &&
ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE));
if (showRationale) {
Toast.makeText(activity,
"Camera permission is needed to run this application", Toast.LENGTH_LONG).show();
} else {
// No explanation needed, we can request the permission.
String permissions[] = requestWritePermission ? new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE}: new String[]{Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(activity,permissions,RC_PERMISSION_REQUEST);
}
}
public static void requestWriteStoragePermission(Activity activity) {
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (showRationale) {
Toast.makeText(activity,
"Writing to external storage permission is needed to run this application",
Toast.LENGTH_LONG).show();
} else {
// No explanation needed, we can request the permission.
String permissions[] = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(activity, permissions, RC_PERMISSION_REQUEST);
}
}
@TargetApi(Build.VERSION_CODES.M)
private void checkPermissionCamera() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.CAMERA)) {
this.requestPermissions(new String[]{Manifest.permission.CAMERA},
Constants.REQUEST_CAMERA_PERMISSION);
} else {
//Camera permissions have not been granted yet so request them directly
this.requestPermissions(new String[]{Manifest.permission.CAMERA},
Constants.REQUEST_CAMERA_PERMISSION);
}
}
}
/**
* 扫描蓝牙设备(判断权限)
*/
void scanLeDevice(boolean enable) {
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (enable) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
SCAN_TRUE_PERMISSION_REQ_CODE);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
SCAN_FALSE_PERMISSION_REQ_CODE);
}
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS)) {
Toast.makeText(this, "开启位置服务才能使用扫描", Toast.LENGTH_SHORT).show();
}
} else {
doScanLeDevice(enable);
}
} else {
doScanLeDevice(enable);
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showRequestPermissionRationale();
} else {
showAppPermissionSettings();
}
}
public void ensurePermission(final @NonNull String permission) {
Builder dialogBuilder = new AlertDialog.Builder(getActivity())
.setCancelable(false);
// FIXME: stop referring to these location permission-specific strings here,
// try to retrieve them from the client
if (ActivityCompat.checkSelfPermission(getActivity(), permission) != PERMISSION_GRANTED ||
ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
dialogBuilder.setTitle(R.string.location_permission_dialog_title)
.setMessage(R.string.location_permission_dialog_text)
.setPositiveButton(R.string.got_it, (dialog, which) -> {
dialog.dismiss();
requestPermission(permission);
});
} else {
// user has explicitly denied this permission to setup.
// show a simple dialog and bail out.
dialogBuilder.setTitle(R.string.location_permission_denied_dialog_title)
.setMessage(R.string.location_permission_denied_dialog_text)
.setPositiveButton(R.string.settings, (dialog, which) -> {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
String pkgName = getActivity().getApplicationInfo().packageName;
intent.setData(Uri.parse("package:" + pkgName));
startActivity(intent);
})
.setNegativeButton(R.string.exit_setup, (dialog, which) -> {
Client client = (Client) getActivity();
client.onUserDeniedPermission(permission);
});
}
dialogBuilder.show();
}
void mayCallPhone() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CALL_PHONE)) {
Toast.makeText(this, "请打开打电话权限来测试", Toast.LENGTH_LONG).show();
}
// 申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQ_CALL_PHONE_CODE);
} else {
doCallPhone();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode != 1000) { return;}
if (grantResults.length <= 0) { return;}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
canClick = true;
onClick(null);
return;
}
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("NOTICE")
.setMessage("PLZ Grant me permission!!")
.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri packageURI = Uri.parse("package:" + getPackageName());
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
startActivity(intent);
}
}).setNegativeButton("Cancel", null).show();
}
}
private Map<String, List<String>> separatePermissions(String[] permissions, String[] rationalMessages) {
Map<String, List<String>> map = new HashMap<>();
List<String> neededPermissions = new ArrayList<>();
List<String> showRationalsFor = new ArrayList<>();
List<String> neededRationalMessages = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
neededPermissions.add(permission);
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
showRationalsFor.add(permission);
// if multiple rational message corresponding to each permission
if (rationalMessages != null && rationalMessages.length == permissions.length) {
neededRationalMessages.add(rationalMessages[i]);
}
}
}
// if rational message is only one
if (rationalMessages != null && rationalMessages.length == 1) {
neededRationalMessages.add(rationalMessages[0]);
}
map.put(NEEDED_PERMISSIONS, neededPermissions);
map.put(SHOW_RATIONAL_FOR, showRationalsFor);
map.put(RATIONALE_MESSAGES_TO_SHOW, neededRationalMessages);
return map;
}
/**
* Handles the requesting of the camera permission. This includes
* showing a "Snackbar" message of why the permission is needed then
* sending the request.
*/
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
/**
* Scan for 5 seconds and then stop scanning when a BluetoothLE device is found then mLEScanCallback is activated This will perform regular scan for custom BLE Service UUID and then filter out
* using class ScannerServiceParser
*/
private void startScan() {
// Since Android 6.0 we need to obtain either Manifest.permission.ACCESS_COARSE_LOCATION or Manifest.permission.ACCESS_FINE_LOCATION to be able to scan for
// Bluetooth LE devices. This is related to beacons as proximity devices.
// On API older than Marshmallow the following code does nothing.
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// When user pressed Deny and still wants to use this functionality, show the rationale
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) && mPermissionRationale.getVisibility() == View.GONE) {
mPermissionRationale.setVisibility(View.VISIBLE);
return;
}
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSION_REQ_CODE);
return;
}
// Hide the rationale message, we don't need it anymore.
if (mPermissionRationale != null)
mPermissionRationale.setVisibility(View.GONE);
mAdapter.clearDevices();
mScanButton.setText(R.string.scanner_action_cancel);
final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
final ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(1000).setUseHardwareBatchingIfSupported(false).setUseHardwareFilteringIfSupported(false).build();
final List<ScanFilter> filters = new ArrayList<>();
filters.add(new ScanFilter.Builder().setServiceUuid(mUuid).build());
scanner.startScan(filters, settings, scanCallback);
mIsScanning = true;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (mIsScanning) {
stopScan();
}
}
}, SCAN_DURATION);
}
/**
* Handles the requesting of the camera permission. This includes
* showing a "Snackbar" message of why the permission is needed then
* sending the request.
*/
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
Snackbar.make(graphicOverlay, R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
/**
* Handles the requesting of the camera permission. This includes
* showing a "Snackbar" message of why the permission is needed then
* sending the request.
*/
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (ContextCompat.checkSelfPermission(LoginActivity.this, permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, permission)) {
return true;
} else {
permissionsList.add(permission);
return false;
}
} else {
return true;
}
}
private void requestPermissionForMicrophone() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(this,
R.string.permissions_needed,
Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.RECORD_AUDIO},
MIC_PERMISSION_REQUEST_CODE);
}
}
void mayCallPhone() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CALL_PHONE)) {
Toast.makeText(this, "请打开打电话权限来测试", Toast.LENGTH_LONG).show();
}
// 申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQ_CALL_PHONE_CODE);
} else {
doCallPhone();
}
}
private static boolean isExplanationNeeded(@NonNull Activity context, @NonNull String permissionName) {
return ActivityCompat.shouldShowRequestPermissionRationale(context, permissionName);
}
@Override
public boolean shouldShowRequestPermissionRationale(@NonNull String perm) {
return ActivityCompat.shouldShowRequestPermissionRationale(getHost(), perm);
}
/**
* Wrapper method for ActivityCompat.shouldShowRequestPermissionRationale().
* Gets whether you should show UI with rationale for requesting a permission.
* You should do this only if you do not have the permission and the context in
* which the permission is requested does not clearly communicate to the user
* what would be the benefit from granting this permission.
*
* @param activity The target activity.
* @param permission A permission to be requested.
* @return Whether to show permission rationale UI.
*/
public static boolean shouldShowRequestPermissionRationale(Activity activity, String permission) {
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}