自从Android6.0后,谷歌增加了许多权限验证,以前只需要权限声明的功能再现在要实现就需要在你执行功能时实时获取权限,即运行时权限runtime permission,下面是我用在程序中获取直接拨打电话的权限的代码,来自网友,亲测好用。
实现代码如下:
复制
/** * 申请权限 */ private void requestPermission() { //判断Android版本是否大于23 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { int checkCallPhonePermission = ContextCompat.checkSelfPermission(SearchActivity.this, Manifest.permission.CALL_PHONE); if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE); return; } else { callPhone(phone); } } else { callPhone(phone); } } /** * 注册权限申请回调 * @param requestCode 申请码 * @param permissions 申请的权限 * @param grantResults 结果 */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { callPhone(phone); } else { // Permission Denied Toast.makeText(SearchActivity.this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } /** * 拨号方法 */ private void callPhone(String phone) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:"+phone)); startActivity(intent); }
在需要获取权限时执行requestPermission();申请权限即可,代码会自动判断是否已经获得授权。
评论 (0)