TrinityTuts Tips

Request for permission in android marshmallow

This tip are for those who creating there app for Android Marshmallow. In android M there are no of good updates for users security but if you are developer it little increase your work at once, now i am going to explain how to add Permission or Request user for permission.

Step 1. In your MainActivity or any class where you need special permission like access camera or read contact etc. Add a static variable which we use to handle results

private static final int Permission_Request = 211;

Step 2. Now inside your onCreate method add check for android and request for permission

if (android.os.Build.VERSION.SDK_INT >= 23) {
            // only for gingerbread and newer versions
            String permission = Manifest.permission.CAMERA;
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            } else {
                // Add your function here which open camera
            }
        } else {
            // Add your function here which open camera
        }

Step 3. Now implement onRequestPermissionsResult method to handle result

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
   // Add your function here which open camera
} else {
 Toast.makeText(getApplication(), "Permission required", Toast.LENGTH_LONG).show(); 
} return; } 
}
}

Now once user allow this setting you can access that thing in your app.

for more also check Working with System Permissions

Hope this help you. 🙂