gpt4 book ai didi

java - Android 联系人权限无需在运行时询问即可授予

转载 作者:行者123 更新时间:2023-12-02 13:22:58 24 4
gpt4 key购买 nike

我正在尝试请求在应用程序中读取联系人的功能,并且已经遵循了几个教程。所有这些都在此过程中使用几乎相同的代码。下面是我的 MainActivity.java 文件中的代码,应该请求权限。

private void checkContactPermissions()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Contacts permission NOT granted");
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
else
{
Log.i(TAG, "Contacts permission granted");
readContacts();
}
}

我的manifest.xml还包含以下行:

<uses-permission android:name="android.permission.READ_CONTACTS" />

当应用程序在模拟器或物理调试设备上运行时,它不会请求权限,但日志会指出已授予权限。我已通过转到设置并检查权限已关闭来确认权限已关闭。还有什么会导致应用程序像授予了权限一样执行。

最佳答案

试试这个,

private Context mContext=YourActivity.this;

private static final int REQUEST = 112;

if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.READ_CONTACTS};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
readContacts();
}
} else {
readContacts();
}

获取权限结果

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts();
} else {
Toast.makeText(mContext, "The app was not allowed to read your contact", Toast.LENGTH_LONG).show();
}
}
}
}

检查棉花糖的权限

private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}

list

<uses-permission android:name="android.permission.READ_CONTACTS" />

关于java - Android 联系人权限无需在运行时询问即可授予,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43493446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com