Android Runtime Permission

The basic of runtime permission as of Android 6.0

Our plan is to make use of Camera and Storage permission. Declare these in the manifest file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Required variable

private static final int REQUEST_ALL_PERMISSION = 1;

Initializing the permission.

Notice in the if statements, we are using two permission at the same time (CAMERA and READ_EXTERNAL_STORAGE). This is called multiple permission. App will pop up a dialog with multiple permission prompt. Remove one of this to use single permission.

private void initPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) ||
                shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Toast.makeText(context, "Need permission please", Toast.LENGTH_SHORT).show();
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_ALL_PERMISSION);
    } else {
        // do your normal stuff

Receiving permission result

If using single permission, make sure to assign a static variable for that particular permission and append more case statements.

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // do your normal stuff
            } else {
                // showing a dialog that directs user to app's detail setting
                AlertDialogUtils.appDetails(this, R.string.permission_appdetails_media);
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Show Comments

Get the latest posts delivered right to your inbox.