我正在更新我们的应用程序,以使用新的M运行时权限系统。
除了onRequestPermissionsResult()之外,它都在工作。我需要检查按下按钮的权限,如果成功,就发送一条短信。当我授权这样做时,对话框会关闭,但直到我再次按下按钮,它才会触发“发送文本”。
我已经在onRequestPermissionsResult()方法中调试和设置了断点,但它从未进入它。
首先调用这个方法:
private void askForPermission() {
String[] permissions = new String[]{Manifest.permission.SEND_SMS};
ActivityCompat.requestPermissions(getActivity(), permissions, PERMISSIONS_CODE);
}
然后我的回调函数是这样的:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_CODE) {
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
int grantResult = grantResults[i];
if (permission.equals(Manifest.permission.SEND_SMS)) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
onPPSButtonPress();
} else {
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSIONS_CODE);
}
}
}
}
}
有人遇到过类似的问题吗?
感谢任何帮助。
谢谢
我有一个类似的问题,除了我按下一个按钮进行调用,这触发了callIntent。我首先检查权限,如果没有授予我要求权限和onRequestPermissionResult我调用检查权限,并再次调用。
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case Constants.PERMISSIONS_REQUEST_CALL_PHONE: {
if ( grantResults[0] == PackageManager.PERMISSION_GRANTED) {
checkPermissionsAndCall();
}
}
}
}
public void checkPermissionsAndCall(){
if (Build.VERSION.SDK_INT > 22) {
if(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, Constants.PERMISSIONS_REQUEST_CALL_PHONE);
}
else{
callIntent();
}
}
}
我发现在调用android.support.v4.app.Fragment.requestPermissions的地方这很重要。
如果你在onCreate()中这样做,onRequestPermissionsResult()永远不会被调用。
解决方案:在onActivityCreated()中调用它;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED)
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 0);
}
对于kotlin用户,这里我的扩展检查和验证权限没有覆盖onRequestPermissionResult
* @param permissionToValidate (request and check currently permission)
*
* @return recursive boolean validation callback (no need OnRequestPermissionResult)
*
* */
internal fun Activity.validatePermission(
permissionToValidate: String,
recursiveCall: (() -> Boolean) = { false }
): Boolean {
val permission = ContextCompat.checkSelfPermission(
this,
permissionToValidate
)
if (permission != PackageManager.PERMISSION_GRANTED) {
if (recursiveCall()) {
return false
}
ActivityCompat.requestPermissions(
this,
arrayOf(permissionToValidate),
110
)
return this.validatePermission(permissionToValidate) { true }
}
return true
}