每当我发送短信时如何解决“显示权限对话框”?

时间:2019-09-19 07:42:10

标签: java android

我想通过android-app发送短信,但是每次都在发送消息之前显示权限对话框,我应该在询问第一个权限后发送没有对话框的消息。

我的android应用在mi-8上运行,目标SDK版本为29。

if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.SEND_SMS}, 3);
} else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 4);
} else {
    sendMsg();
}

我希望在第一个请求的权限之后发送消息时,权限对话框没有显示,但是每次发送消息时,每次显示对话框时都会显示。

1 个答案:

答案 0 :(得分:0)

使用此功能来检查您是否已授予许可(如果说),那么您已按要求获得许可,它将返回true标志

通过这种方式检查

   private boolean checkAndRequestPermissions(){

        //add as much as permission you need
        int readSMS = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
        int sendSms = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS);

        List<String> listPermissionsNeeded = new ArrayList<>();

        if (readSMS != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (receiveSms != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                    REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

通过这种方式检查

 if (checkAndRequestPermissions()){
        sendMsg();
    }else{
      //do what you want  
    }

无需通过硬编码方式做到这一点