我是关于android的新手。我想制作一个功能,检查我的电话簿中是否已有电话号码。 我在清单上添加了阅读联系人权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />
我无法每次都获得阅读联系人和我的应用程序崩溃的权限。
答案 0 :(得分:1)
基本上,在从危险权限列表中执行操作之前,您必须先检查您是否拥有权限
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR);
如果它返回您的应用程序未被授予,那么您需要在运行时请求它。
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
所以,将代码放在第一个&#34之后;如果&#34; &#34; else&#34;块。
如果您还有其他问题,请与我们联系。
答案 1 :(得分:0)
您可以在Android Marshmallow here中了解有关新权限模型的所有信息。
在尝试执行任何操作之前,您必须检查dangerous permissions是否有权限。
使用以下代码检查并询问权限:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
并查看用户是否已接受或拒绝了权限请求:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}