简体   繁体   English

Android 请求运行时权限时应用程序退出

[英]Android App exits when request Runtime Permissions

In the program below I ask for SMS permission before sending a message.在下面的程序中,我在发送消息之前请求 SMS 许可。

At first App execution, when the message request is confirmed, the permission are checked and, if missing, a pop up requesting the user to allow the app is issued.在第一次应用程序执行时,当消息请求被确认时,会检查权限,如果没有,则会发出一个请求用户允许应用程序的弹出窗口。

When this pop up is issued, the app is moved in background.发出此弹出窗口时,应用程序将在后台移动。

I found many topics about this issue but no fixes for my problem.我发现了很多关于这个问题的主题,但没有解决我的问题。 Eg the nohistory entry is missing in the manifest.例如,清单中缺少 nohistory 条目。

private void checkForSmsPermission() {

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.SEND_SMS) !=
            PackageManager.PERMISSION_GRANTED) {
     
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.SEND_SMS},
                MY_PERMISSIONS_REQUEST_SEND_SMS);
        return;

    } else {
        // Permission already granted. Enable the SMS button.
        return;
    }
}



@Override
public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_SEND_SMS)  {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
            }
        }
    }

public void send_command (String text){

    checkForSmsPermission();


    //Get the SmsManager instance and call the sendTextMessage method to send message
    SmsManager sms=SmsManager.getDefault();
    sms.sendTextMessage(recipient_number, null, text, null,null);


}

This is happening because you are calling following method anyways.发生这种情况是因为您无论如何都在调用以下方法。

SmsManager sms=SmsManager.getDefault();
 sms.sendTextMessage(recipient_number, null, text, null,null);

You should only call them if you are sure that you have the permission else your app will crash.如果您确定您有权限,您应该只给他们打电话,否则您的应用程序将崩溃。 Its always recommended to call these method on success of permission validation.始终建议在权限验证成功时调用这些方法。 but in your case it will get call whether the user provided the permission or not.但在您的情况下,无论用户是否提供了权限,它都会被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM