Request permissions based on API level

二次信任 提交于 2019-11-30 23:06:18
  • You can't request a Permission which is not declared in Manifest.
  • You can't change your Manifest at runtime.

What you can do is to make 1 flavor targeting API 23+ with permission declared and another flavor without the permission targeting API 23-.

I think you can do this using:

<uses-permission-sdk-23 android:name="string" android:maxSdkVersion="integer" />

You can read more about it in the official documentation: uses-permission-sdk-23

no that's not possible in AndroidManifest.xml

you can ask the permission before using the functions based on the that permission.

if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.ACCESS_FINE_LOCATION) 
        != PackageManager.PERMISSION_GRANTED) {

           //Ask for permission
           ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                requestCode); 

}else{

//already permitted . Do your work here..
}

now override onRequestPermissionsResult() Method to see if user permitted the request or not

@Override 
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {

            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission is granted, Now you can execute function 

            } else { 

                // permission denied, Don't execute your function to avoid any crashes

            } 
            return; 

}

you don't have to check for SDK version here for more information click here Happy Coding :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!