[android] How to check Grants Permissions at Run-Time?

In Android M (Preview) the user can choose a specific app and retreive specific permission.

So I am asking How to check Grants Permissions at Run-Time?

The answer is


Check out the below library in git :

RuntimePermission

Implementation :

        allprojects {
            repositories {
                ...
                maven { url 'https://jitpack.io' }
            }
        }
        
        dependencies {
            implementation 'com.github.manoj140220:RuntimePermission:1.0.3'
        }
    
    
      
    
        new RuntimePermission({Current Class Object}, String[] , {ActvityContext});
          
          String[] : permission array.
          example  : String[] permissionArray = {Manifest.permission.CAMERA, Manifest.permission.BODY_SENSORS,...} 
    
    Implement : {PermissionNotify}
    
    interface notifier methods.
    
    @Override
    public void notifyPermissionGrant() {
        
    }
    
    @Override
    public void notifyPermissionDeny() {
         
    }

fun hasPermission(permission: String): Boolean {
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true // must be granted after installed.
      return mAppSet.appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}

You can also query by following code snippet as backward compatible;

int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
    //Do smthng
}

use Dexter library

Include the library in your build.gradle

dependencies{
    implementation 'com.karumi:dexter:4.2.0'
}

this example requests WRITE_EXTERNAL_STORAGE.

Dexter.withActivity(this)
                .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        // permission is granted, open the camera
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        // check for permanent denial of permission
                        if (response.isPermanentlyDenied()) {
                            // navigate user to app settings
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();

check this answer here


Try this for Check Run-Time Permission:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkRunTimePermission();
}

Check run time permission:

private void checkRunTimePermission() {
    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(permissionArrays, 11111);
    } else {
         // if already permition granted
        // PUT YOUR ACTION (Like Open cemara etc..)
    }
}

Handle Permission result:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == 11111) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission
                boolean showRationale = shouldShowRequestPermissionRationale(permission);
                if (!showRationale) {
                    //execute when 'never Ask Again' tick and permission dialog not show
                } else {
                    if (openDialogOnce) {
                        alertView();
                    }
                }
            }
        }

        if (isPermitted)
            if (isPermissionFromGallery)
                openGalleryFragment();
    }
}

Set custom alert:

private void alertView() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);

    dialog.setTitle("Permission Denied")
            .setInverseBackgroundForced(true)
            //.setIcon(R.drawable.ic_info_black_24dp)
            .setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")

            .setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                }
            })
            .setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                    checkRunTimePermission();

                }
            }).show();
}


original (not mine) post here

For special permissions, such as android.Manifest.permission.PACKAGE_USAGE_STATS used AppOpsManager:
Kotlin

private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean {
    var granted = false
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
        // requires kitkat
        val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager

        // requires lollipop
        val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
                              android.os.Process.myUid(), applicationContext!!.packageName)

        if (mode == AppOpsManager.MODE_DEFAULT) {
            granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
        } else {
            granted = mode == AppOpsManager.MODE_ALLOWED
        }
    }

    return granted
}

and anywhere in code:

val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS

if (hasPermission(permission, permissionAppOpsManager)) {
    Timber.i("has permission: $permission")
    // do here what needs permission
} else {
    Timber.e("has no permission: $permission")
    // start activity to get permission
    startActivity(Intent(permissionActivity))
}

Other permissions you can get with TedPermission library


Try this instead simple request code
https://www.learn2crack.com/2015/10/android-marshmallow-permissions.html

public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

private  boolean checkAndRequestPermissions() {
    int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
    int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
    int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camera != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
    }
    if (storage != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (loc2 != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    }
    if (loc != PackageManager.PERMISSION_GRANTED) {
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    if (!listPermissionsNeeded.isEmpty())
    {
        ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray
                (new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    }
    return true;
}

For Location runtime Permission

ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("yes","yes");

            } else {
                Log.d("yes","no");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-permissions

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied) Android 6.0 multiple permissions Android marshmallow request permission? How to programmatically open the Permission Screen for a specific app on Android Marshmallow? Android M Permissions: onRequestPermissionsResult() not being called Android M - check runtime permission - how to determine if the user checked "Never ask again"? How to check Grants Permissions at Run-Time? How to detect incoming calls, in an Android device? Exception 'open failed: EACCES (Permission denied)' on Android What permission do I need to access Internet from an Android application?

Examples related to android-6.0-marshmallow

Android 6.0 multiple permissions How to check the multiple permission at single request in Android M? Android marshmallow request permission? Get JSON Data from URL Using Android? Storage permission error in Marshmallow Android 6.0 Marshmallow. Cannot write to SD Card How to programmatically open the Permission Screen for a specific app on Android Marshmallow? Neither user 10102 nor current process has android.permission.READ_PHONE_STATE ConnectivityManager getNetworkInfo(int) deprecated getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)