Permission - Krunal-Kevadiya/kotlin-common GitHub Wiki

Android RuntimePermissions Sample

This sample shows runtime permissions available in Android M and above. It shows how to check and request permissions at runtime, handle backwards compatibility using the support library and how to declare optional permissions for M-devices only.

Introduction

Android M introduced runtime permissions. Applications targeting M and above need to request their permissions at runtime. All permissions still need to be declared in the AndroidManifest. However, when accessing APIs that require a permission, the Activity or Fragment has to verify that the permission has been granted or request the missing permissions using calls through the support library. Permissions are checked through ActivityCompat.checkSelfPermission(Context, String) or ContextCompat.checkSelfPermission(Context, String). Permission are requested through ActivityCompat.requestPermissions(Activity, String[], int), and the response received in a callback to ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[]). Applications can provide an additional rational for the use of permissions after calling ActivityCompat.shouldShowRequestPermissionRationale(Activity,String). This call will return true if the application should provide the user with more context on why the requested permissions is needed, for example if the permission request has been denied before.

If an application targets an SDK below M, all permissions are granted at runtime and are available when the application is running. The support library calls handle these checks appropriately. However, if permissions have been turned off in the system settings for an application targeting an SDK below M, the API will return empty or no data.

  • Before you have used
public class MultiplePermissionsActivity extends AppCompatActivity {
 
    private static final int PERMISSION_CALLBACK_CONSTANT = 100;
    private static final int REQUEST_PERMISSION_SETTING = 101;
    String[] permissionsRequired = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};
    private TextView txtPermissions;
    private Button btnCheckPermissions;
    private SharedPreferences permissionStatus;
    private boolean sentToSettings = false;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multiple_permissions);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        permissionStatus = getSharedPreferences("permissionStatus",MODE_PRIVATE);
 
        txtPermissions = (TextView) findViewById(R.id.txtPermissions);
        btnCheckPermissions = (Button) findViewById(R.id.btnCheckPermissions);
 
        btnCheckPermissions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ActivityCompat.checkSelfPermission(MultiplePermissionsActivity.this, permissionsRequired[0]) != PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(MultiplePermissionsActivity.this, permissionsRequired[1]) != PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(MultiplePermissionsActivity.this, permissionsRequired[2]) != PackageManager.PERMISSION_GRANTED){
                    if(ActivityCompat.shouldShowRequestPermissionRationale(MultiplePermissionsActivity.this,permissionsRequired[0])
                            || ActivityCompat.shouldShowRequestPermissionRationale(MultiplePermissionsActivity.this,permissionsRequired[1])
                            || ActivityCompat.shouldShowRequestPermissionRationale(MultiplePermissionsActivity.this,permissionsRequired[2])){
                        //Show Information about why you need the permission
                        AlertDialog.Builder builder = new AlertDialog.Builder(MultiplePermissionsActivity.this);
                        builder.setTitle("Need Multiple Permissions");
                        builder.setMessage("This app needs Camera and Location permissions.");
                        builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                ActivityCompat.requestPermissions(MultiplePermissionsActivity.this,permissionsRequired,PERMISSION_CALLBACK_CONSTANT);
                            }
                        });
                        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        builder.show();
                    } else if (permissionStatus.getBoolean(permissionsRequired[0],false)) {
                        //Previously Permission Request was cancelled with 'Dont Ask Again',
                        // Redirect to Settings after showing Information about why you need the permission
                        AlertDialog.Builder builder = new AlertDialog.Builder(MultiplePermissionsActivity.this);
                        builder.setTitle("Need Multiple Permissions");
                        builder.setMessage("This app needs Camera and Location permissions.");
                        builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                sentToSettings = true;
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                                Toast.makeText(getBaseContext(), "Go to Permissions to Grant  Camera and Location", Toast.LENGTH_LONG).show();
                            }
                        });
                        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                        builder.show();
                    }  else {
                        //just request the permission
                        ActivityCompat.requestPermissions(MultiplePermissionsActivity.this,permissionsRequired,PERMISSION_CALLBACK_CONSTANT);
                    }
 
                    txtPermissions.setText("Permissions Required");
 
                    SharedPreferences.Editor editor = permissionStatus.edit();
                    editor.putBoolean(permissionsRequired[0],true);
                    editor.commit();
                } else {
                    //You already have the permission, just go ahead.
                    proceedAfterPermission();
                }
            }
        });
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PERMISSION_CALLBACK_CONSTANT){
            //check if all permissions are granted
            boolean allgranted = false;
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    allgranted = true;
                } else {
                    allgranted = false;
                    break;
                }
            }
 
            if(allgranted){
                proceedAfterPermission();
            } else if(ActivityCompat.shouldShowRequestPermissionRationale(MultiplePermissionsActivity.this,permissionsRequired[0])
                    || ActivityCompat.shouldShowRequestPermissionRationale(MultiplePermissionsActivity.this,permissionsRequired[1])
                    || ActivityCompat.shouldShowRequestPermissionRationale(MultiplePermissionsActivity.this,permissionsRequired[2])){
                txtPermissions.setText("Permissions Required");
                AlertDialog.Builder builder = new AlertDialog.Builder(MultiplePermissionsActivity.this);
                builder.setTitle("Need Multiple Permissions");
                builder.setMessage("This app needs Camera and Location permissions.");
                builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        ActivityCompat.requestPermissions(MultiplePermissionsActivity.this,permissionsRequired,PERMISSION_CALLBACK_CONSTANT);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            } else {
                Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
            }
        }
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PERMISSION_SETTING) {
            if (ActivityCompat.checkSelfPermission(MultiplePermissionsActivity.this, permissionsRequired[0]) == PackageManager.PERMISSION_GRANTED) {
                //Got Permission
                proceedAfterPermission();
            }
        }
    }
 
    private void proceedAfterPermission() {
        txtPermissions.setText("We've got all permissions");
        Toast.makeText(getBaseContext(), "We got All Permissions", Toast.LENGTH_LONG).show();
    }
 
    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (sentToSettings) {
            if (ActivityCompat.checkSelfPermission(MultiplePermissionsActivity.this, permissionsRequired[0]) == PackageManager.PERMISSION_GRANTED) {
                //Got Permission
                proceedAfterPermission();
            }
        }
    }
}
  • After library used
class PermissionActivity : AppCompatActivity() {

    private val textView: TextView by lazy {
        findViewById<TextView>(R.id.textView)
    }

    fun appendText(textView: TextView, text: String) {
        textView.post { textView.text = textView.text.toString() + "\n" + text }
    }

    //Using Lazy DSL
    private val permission: RuntimePermission by
        bindPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE){
            setResult(it)
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_permission)

        findViewById<Button>(R.id.btn_permission).setOnClickListener {
            //Using Extension DSL
            /*askPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE) {
                setResult(it)
            }.ask()*/

            //Using Manually
            /*RuntimePermission(this@PermissionActivity)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .onResponse { setResult(it) }
                .ask()*/
            permission.ask()
        }
    }

    private fun setResult(it: PermissionCallback) {
        with(it) {
            if (hasAccepted()) {
                textView.text = "Accepted :${accepted}"
            }

            if (hasDenied()) {
                appendText(textView, "Denied :")
                appendText(textView, "$denied")

                AlertDialog.Builder(this@PermissionActivity)
                    .setMessage("Please accept our permissions to denied")
                    .setPositiveButton("yes") { dialog, which ->
                        askAgain()
                    }
                    .setNegativeButton("no") { dialog, which ->
                        dialog.dismiss()
                    }
                    .show()
            }

            if (hasForeverDenied()) {
                appendText(textView, "ForeverDenied :")
                appendText(textView, "$foreverDenied")

                AlertDialog.Builder(this@PermissionActivity)
                    .setMessage("Please accept our permissions foreverDenied")
                    .setPositiveButton("yes") { dialog, which ->
                        goToSettings()
                    }
                    .setNegativeButton("no") { dialog, which ->
                        dialog.dismiss()
                    }
                    .show()
            }
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️