为了更好的保护了用户的隐私,在Google发布的android6.0中推出了新的权限机制,Google将权限分为两类,一类是Normal Permissions,这类权限一般不涉及用户隐私,是不需要用户进行授权的,比如手机震动、访问网络等;另一类是Dangerous Permission,当app需要用户授予不恰当的权限的时候,用户可以拒绝,一般是涉及到用户隐私的,需要用户进行授权,当app需要用户授予不恰当的权限的时候,用户可以拒绝,比如读取sdcard、访问通讯录等。
一、运行权限管理
当我们在开发中做访问通讯录、拨打电话等操作时,Android Studio就会给我们下面的提示:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermission`) or explicitly handle a potential `SecurityException`
当我们点击”Add permission check”时:
Android Studio就会为我们添加如下代码:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
然后我们对这段代码做下处理,处理后实例代码如下:
public void callPhone() {
Intent intent = new Intent(Intent.ACTION_CALL);
Uri data = Uri.parse("tel:" + "10086");
intent.setData(data);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
} else {
startActivity(intent);
}
}
然后对申请权限处理后的返回数据做一下处理,代码如下:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callPhone();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
注意:
申请权限也需要添加权限,必须要在清单文件中添加权限,否则点击拨打电话无效果:
<uses-permission android:name="android.permission.CALL_PHONE" />
到了这里咱们就处理完了,让我们看一下运行效果:
到了这里小伙伴们应该知道怎么用了吧。希望这篇博客能够为小伙伴们提供一些帮助。