Monday, April 3, 2017

How to get permission in android api level 23 and above at runtime?????.....

App Permission


Hi guyz,

Today I'm going to share how to get permission in android API level 23 and above during runtime...

for some security reason, you need to ask the permission of the user at runtime in Marshmellow and above...

below is the code to check whether the user had permission or not...

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)) {
                     //got permission
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        2);
            }
        }



below code is to do perform some action after the user's input...


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                }
                return;
            }
            case 2: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                }
                return;
            }
        }
    }


Note: you have to specify the permission in manifest.xml file as


    <permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

#RajeshDeveloper