Java Code Examples for android.support.v4.app.ActivityCompat#shouldShowRequestPermissionRationale()

The following examples show how to use android.support.v4.app.ActivityCompat#shouldShowRequestPermissionRationale() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainActivity.java    From QrCodeLib with MIT License 6 votes vote down vote up
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);
}
 
Example 2
Source File: DeviceScanActivity.java    From IoT-Firstep with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 扫描蓝牙设备(判断权限)
 */
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);
    }
}
 
Example 3
Source File: NewTransferFragment.java    From android-wallet-app with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example 4
Source File: PermissionHelper.java    From mobile-ar-sensor-logger with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: PermissionHelper.java    From grafika with Apache License 2.0 6 votes vote down vote up
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);
      }
    }
 
Example 6
Source File: ScannerFragment.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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);
}
 
Example 7
Source File: MainActivity.java    From IoT-Firstep with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example 8
Source File: AudioSinkActivity.java    From video-quickstart-android with MIT License 5 votes vote down vote up
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);
    }
}
 
Example 9
Source File: LoginActivity.java    From ESeal with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 10
Source File: OcrCaptureActivity.java    From Questor with MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example 11
Source File: OcrCaptureActivity.java    From android-vision with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 12
Source File: FaceFilterActivity.java    From Android-face-filters with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source File: AskActivity.java    From Muzesto with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: MainActivity.java    From Glin with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 15
Source File: MainActivity.java    From IoT-Firstep with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
}
 
Example 16
Source File: PermissionsFragment.java    From spark-setup-android with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 17
Source File: HelperActivity.java    From AwesomeImagePicker with Apache License 2.0 5 votes vote down vote up
private void requestPermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showRequestPermissionRationale();

    } else {
        showAppPermissionSettings();
    }
}
 
Example 18
Source File: AppCompatActivityPermissionHelper.java    From BaseProject with MIT License 4 votes vote down vote up
@Override
public boolean shouldShowRequestPermissionRationale(@NonNull String perm) {
    return ActivityCompat.shouldShowRequestPermissionRationale(getHost(), perm);
}
 
Example 19
Source File: ActivityHelper.java    From mvvm-template with GNU General Public License v3.0 4 votes vote down vote up
private static boolean isExplanationNeeded(@NonNull Activity context, @NonNull String permissionName) {
    return ActivityCompat.shouldShowRequestPermissionRationale(context, permissionName);
}
 
Example 20
Source File: PermissionUtil.java    From Cirrus_depricated with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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);
}