1.先定义一个常量数组,把Manifest中声明的权限加进去,如下:
/** * 所需的所有权限信息 */ private static final String[] NEEDED_PERMISSIONS = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE };
2.调用checkPermissions
private boolean checkPermissions(String[] neededPermissions) { if (neededPermissions == null || neededPermissions.length == 0) { return true; } boolean allGranted = true; for (String neededPermission : neededPermissions) { allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED; } return allGranted; }
如果没有获取到权限,需要重新申请
ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
ACTION_REQUEST_PERMISSIONS是一个常量,用于requestCode :
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == ACTION_REQUEST_PERMISSIONS) { boolean isAllGranted = true; for (int grantResult : grantResults) { isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED); } if (isAllGranted) { } else { Toast.makeText(this, "ssss", Toast.LENGTH_SHORT).show(); } } }