Java ActivityCompat.requestPermissions 未显示对话框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35484767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ActivityCompat.requestPermissions not showing dialog box
提问by Idan Ayzen
if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE_PERMISSION);
i'm trying to use this function on nexus 5 api 23 and its just not showing me the dialog box like its supposed to do, it's just not doing anything. what could cause the problem? (this code is in the java activity) i tried changing my minimum api to 23 and use the requestPermissions() without the ActivityCompat but still not working.
我正在尝试在 nexus 5 api 23 上使用这个函数,它只是没有像它应该做的那样向我显示对话框,它只是没有做任何事情。什么可能导致问题?(此代码在 java 活动中)我尝试将我的最小 api 更改为 23 并使用没有 ActivityCompat 的 requestPermissions() 但仍然无法正常工作。
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.idanayzen.photomap"
minSdkVersion 23
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.android.support:design:23.1.1'
}
and the Manifest:
和清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.idanayzen.photomap">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" />
<activity android:name=".RegisterActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WrongPhoneNum"></activity>
</application>
</manifest>
采纳答案by NightSkyDev
Here's an example of using requestPermissions()
:
这是使用的示例requestPermissions()
:
First, define the permission (as you did in your post) in the manifest, otherwise, your request will automatically be denied:
首先,在清单中定义权限(就像您在帖子中所做的那样),否则,您的请求将自动被拒绝:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Next, define a value to handle the permission callback, in onRequestPermissionsResult():
接下来,在 onRequestPermissionsResult() 中定义一个值来处理权限回调:
private final int REQUEST_PERMISSION_PHONE_STATE=1;
Here's the code to call requestPermissions():
这是调用 requestPermissions() 的代码:
private void showPhoneStatePermission() {
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
showExplanation("Permission Needed", "Rationale", Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
} else {
requestPermission(Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
}
} else {
Toast.makeText(MainActivity.this, "Permission (already) Granted!", Toast.LENGTH_SHORT).show();
}
}
First, you check if you already have permission (remember, even after being granted permission, the user can later revoke the permission in the App Settings.)
首先,您检查您是否已经拥有权限(请记住,即使在被授予权限后,用户也可以稍后在应用设置中撤销该权限。)
And finally, this is how you check if you received permission or not:
最后,这是您检查是否获得许可的方式:
@Override
public void onRequestPermissionsResult(
int requestCode,
String permissions[],
int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_PHONE_STATE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
private void showExplanation(String title,
String message,
final String permission,
final int permissionRequestCode) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
requestPermission(permission, permissionRequestCode);
}
});
builder.create().show();
}
private void requestPermission(String permissionName, int permissionRequestCode) {
ActivityCompat.requestPermissions(this,
new String[]{permissionName}, permissionRequestCode);
}
回答by CommonsWare
Replace:
代替:
ActivityCompat.requestPermissions(this, new String[]{"Manifest.permission.READ_PHONE_STATE"}, 225);
with:
和:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 225);
The actual string for that permissionis not "Manifest.permission.READ_PHONE_STATE"
. Use the symbol Manifest.permission.READ_PHONE_STATE
.
该权限的实际字符串不是"Manifest.permission.READ_PHONE_STATE"
. 使用符号Manifest.permission.READ_PHONE_STATE
。
回答by Bk245
I had this same issue.I updated to buildToolsVersion "23.0.3"It all of a sudden worked. Hope this helps anyone having this issue.
我有同样的问题。我更新到buildToolsVersion "23.0.3"它突然起作用了。希望这可以帮助任何遇到此问题的人。
回答by Meanman
For me the issue was requesting a group mistakenly instead of the actual permissions.
对我来说,问题是错误地请求了一个组而不是实际的权限。
回答by hrunk
I had the same issue and it turned out to be due to the manifest merger toolpulling in an android:maxSdkVersion
attribute from a dependency.
我遇到了同样的问题,结果是由于清单合并工具android:maxSdkVersion
从依赖项中提取了一个属性。
To view the actual permissions you're requesting in your APK you can use the aapt
tool, like this:
要查看您在 APK 中请求的实际权限,您可以使用该aapt
工具,如下所示:
/path/to/android-sdk/build-tools/version/aapt d permissions /path/to/your-apk.apk
in my case, it printed:
就我而言,它打印:
uses-permission: name='android.permission.WRITE_EXTERNAL_STORAGE' maxSdkVersion='18'
even though I hadn't specified a maxSdkVersion
in my manifest. I fixed this issue by changing <uses-permission>
in my manifest to:
即使我没有maxSdkVersion
在清单中指定 a 。我通过将<uses-permission>
清单更改为以下内容来解决此问题:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:remove="android:maxSdkVersion"/>
(where the tools namespace is http://schemas.android.com/tools
)
(工具命名空间所在的位置http://schemas.android.com/tools
)
回答by Shyam Sunder
I updated my target SDK version from 22 to 23 and it worked perfectly.
我将我的目标 SDK 版本从 22 更新到 23,它运行良好。
回答by Beaux
I was having the same problem, and solved it by replacing Manifest.permission.READ_PHONE_STATE with android.Manifest.permission.READ_PHONE_STATE.
我遇到了同样的问题,并通过用 android.Manifest.permission.READ_PHONE_STATE 替换 Manifest.permission.READ_PHONE_STATE 来解决它。
回答by griffin2000
For me the issue was I had an invalid request code. I choose 0xDEADBEEF as a request code and it was silently failing (maybe it's cast to something smaller than 32-bit somewhere internally?) If I choose 255 everything worked fine as NightSkyDev described above.
对我来说,问题是我有一个无效的请求代码。我选择 0xDEADBEEF 作为请求代码并且它默默地失败了(也许它在内部某个地方被转换为小于 32 位的东西?)如果我选择 255 一切正常,就像上面描述的 NightSkyDev 一样。
回答by Eliot Gillum
The above information is good, but setting targetSdkVersion
to 23 (or higher) is criticalfor Android to interpret the <uses-permission>
tag in the manifest as "I will ask in code" instead of "I demand upon installation." Lots of sources will tell you that you need the <uses-permission>
tag, but no one says why and if you don't have that value set, you're going to be as confused as I was for hours on end.
上述信息很好,但设置targetSdkVersion
为 23(或更高)对于 Android将清单中的标签解释为“我会在代码中询问”而不是“我要求在安装时”至关重要<uses-permission>
。许多消息来源会告诉您需要该<uses-permission>
标签,但没有人说明原因,如果您没有设置该值,您将像我一样困惑数小时。
回答by Benjamin H
This just happened to me. It turned out I was requesting ALL permissions, when I needed to filter to just DANGEROUS permissions, and it suddenly started working.
这只是发生在我身上。结果我请求所有权限,当我需要过滤到危险权限时,它突然开始工作。
fun requestPermissions() {
val missingDangerPermissions = PERMISSIONS
.filter { ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED }
.filter { this.getPackageManager().getPermissionInfo(it, PackageManager.GET_META_DATA).protectionLevel == PermissionInfo.PROTECTION_DANGEROUS } // THIS FILTER HERE!
if (missingDangerPermissions.isNotEmpty()) {
Log.i(TAG, "Requesting dangerous permission to $missingDangerPermissions.")
ActivityCompat.requestPermissions(this,
missingDangerPermissions.toTypedArray(),
REQUEST_CODE_REQUIRED_PERMISSIONS);
return
} else {
Log.i(TAG, "We had all the permissions we needed (yay!)")
}
}