Hello world, I prepared a PermissionsUtil.java class and it’s on GitHub.
Check it out: AndroidPermissionsUtil
Why use it? It will help by letting you write less code as you add conditions to your Android app that supports Android 6.0 (Marshmallow). The utility class defines helper methods that were used in the following example.
Sample usage of Android M PermissionUtils
On the activity where you need to check for runtime permissions, add these:
1 2 3 4 5 6 7 8 9 10 11 12 |
private final int REQ_CODE_PERMS_FEATURE01 = 1; String[] NEEDED_PERMS_FEATURE01 = { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }; final PermissionsUtil permUtil = new PermissionsUtil(MainActivity.this); permUtil.setNeededPermissions(NEEDED_PERMS_FEATURE01); permUtil.setPermissionsRequestCode(REQ_CODE_PERMS_FEATURE01); if(permUtil.allRequiredPermissionsGranted()){ // proceed with what requires permission(s) } else { permUtil.requestNeededPermissions(); } |
And add the callback function to the same activity:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQ_CODE_PERMS_FEATURE01) { Boolean permissionRequestResult = permUtil.processPermissionsRequestResult(requestCode, permissions, grantResults); if(permissionRequestResult){ // proceed to do what needed permission(s) } else { // oops, user denied permission request } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } |
Feel free to use in on any project. And please let me know if you have suggestions on how to improve that Android M runtime permissions utility class.