androidandroid-studioruntime-permissions

Android Studio is not recognizing runtime permission code


I'm trying to implement runtime permissions (targeting SDK 24), but Android Studio doesn't seem to recognize all the code.

Everything is fine until I get to ".READ_CONTACTS" or ".CAMERA." Also, "requestPermissions." turns red as well. I've tried importing various things, such as "android.support.v4.content.ContextCompat" to no avail.

if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED){
            yeahReadContacts();
        }else{
            requestPermissions. //This and "READ_CONTACTS" are red.
        }}

Also, I'm calling this from a custom dialog class, but I didn't think that should be a problem, as these are supposed to be "run-time" permissions, right??

Example of runtime permissions code turning red


Solution

  • I figured out both problems, with the help of @Enzokie.

    The .READ_CONTACTS part of Manifest.permission.READ_CONTACTS because I had somehow created a file called Manifest.java, and needed to rename it to something like ManifestNot.java, because it was conflicting with the Manifest library feature.

    Secondly, the library function requestPermissions was red because I was calling it from a Dialog, and needed to prefix it with mActivity, which was an Activity object I created and initialized in the constructor method of my dialog:

    Activity mActivity; //Declared
    
    //The constructor
    public AddEntityDialog(Context context) {
        super(context);
        mActivity = (Activity) context;
    }
    

    Of course I needed to define a couple arguments that requestPermissions requires as follows, but then I was able to write the code without it becoming red.

    String[] perms = {"android.permission.READ_CONTACTS"};
    int permsRequestCode = 100; //This can be any number
    

    Then the final line is no longer red:

    mActivity.requestPermissions(perms, permsRequestCode);
    

    Here's a good chunk of the code for better context:

    public void readContacts(){
    
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED){
            yeahReadContacts();
        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                mActivity.requestPermissions(perms, permsRequestCode);
            }
        }
    }