我要求ACCESS_COARSE_LOCATION
权限,但没有出现对话框。
这是我的代码:
if (!checkPermissions()) {
requestPermissions();
} else {
getLastLocation();
}
这是requestPermission()
:
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
// Provide an additional rationale to the user. This would happen if the user denied the
// request previously, but didn't check the "Don't ask again" checkbox.
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
builder1.setMessage("Location permission is needed in order to show your current location");
builder1.setCancelable(true);
builder1.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.RECORD_AUDIO},
PERMISSION_REQUEST_RECORD_AUDIO);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
} else {
Log.i(TAG, "Requesting permission");
// Request permission. It's possible this can be auto answered if device policy
// sets the permission in a given state or the user denied the permission
// previously and checked "Never ask again".
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
我打印出08-31 13:02:25.067 8231-8231/com.appName.app/com.appName.app.MainActivity: Requesting permission
但没有出现询问权限的对话框。
为什么会这样?
答案 0 :(得分:0)
试试这个
String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, 123);
}
现在处理permisiion结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_GPS_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "location_permission_granted ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "location_permission_not_granted ", Toast.LENGTH_SHORT).show();
}
}
}
请勿忘记在清单文件中添加此权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
答案 1 :(得分:0)
抱歉这个愚蠢的错误。
我弄明白了这个问题。我忘了在<uses-permission>
中添加AndroidManifest.xml
标记。
添加:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<{1}} AndroidManifest.xml
标记下的完成了这项工作。