ythy / blog

Give everything a shot
6 stars 0 forks source link

Android requestPermission #160

Open ythy opened 5 years ago

ythy commented 5 years ago

Requests permissions to be granted to this application. These permissions must be requested in your manifest.

If your app does not have the requested permissions the user will be presented with UI for accepting them. After the user has accepted or rejected the requested permissions you will receive a callback ononRequestPermissionsResult(int, String[], int[]) reporting whether the permissions were granted or not.

Note that requesting a permission does not guarantee it will be granted and your app should be able to run without having this permission.

You cannot request a permission if your activity sets noHistory to true because in this case the activity would not receive result callbacks including onRequestPermissionsResult(int, String[], int[]).

A sample example:

val MY_PERMISSIONS_REQUEST:Int = 102

fun requestPermission(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(arrayOf(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, 
                Manifest.permission.WRITE_EXTERNAL_STORAGE),
                MY_PERMISSIONS_REQUEST)
    };
}

override fun onRequestPermissionsResult(requestCode: Int, 
permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if(requestCode != MY_PERMISSIONS_REQUEST){
        Toast.makeText(this, "Error", Toast.LENGTH_LONG).show()
    }
}
ythy commented 5 years ago

验证是否有某个权限

private boolean checkWriteExternalPermission()
{
    String permission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    int res = getContext().checkCallingOrSelfPermission(permission);
    return (res == PackageManager.PERMISSION_GRANTED);            
}