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.

@TargetApi(Build.VERSION_CODES.M)
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.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {  
    switch (requestCode) {
        case REQUEST_ALL_PERMISSION:
            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);
            }
            return;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Aiman Baharum

More about this blog https://github.com/aimanbaharum/random-wiki/wiki

Kuala Lumpur, Malaysia http://www.aimanbaharum.com

Subscribe to Knowledge Log

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!