我正在尝试发送具有运行时权限的短信目标版本24。它在Redmi Mi 3s设备中提供SecurityException,但在具有棉花糖OS的其他设备上也可以正常工作。

final int REQ_CODE = 100;
void requestPermission(){
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
        CTLogs.printLogs( "Permission is not granted, requesting");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS,Manifest.permission.READ_SMS,Manifest.permission.RECEIVE_SMS}, REQ_CODE);
       // button.setEnabled(false);
    } else {
        CTLogs.printLogs("Permission has been granted");
        sendSMS();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQ_CODE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            CTLogs.printLogs("Permission has been granted");
            sendSMS();
           } else {
            CTLogs.printLogs("Permission denied !!!");
        }
    }
}

最佳答案

尝试这个:

// The permission required by the application to work properly
    protected static final String[] requiredPermissions;
    private static final int PERMISSION_REQUEST = 0;

    static {
        List<String> perms = new ArrayList<>(Arrays.asList(
                Manifest.permission.RECEIVE_SMS,
                Manifest.permission.READ_SMS,
                Manifest.permission.SEND_SMS
        ));
        requiredPermissions = perms.toArray(new String[perms.size()]);
    }


在onCreate()中调用verifyPermissions()方法:

private void verifyPermissions() {
        if (!hasAllPermissions()) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    requiredPermissions,
                    PERMISSION_REQUEST
            );
        }
    }

    private boolean hasAllPermissions() {
        // Check if we have all required permissions.
        for (String perm : requiredPermissions) {
            if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST: {
                // If request is cancelled, the result arrays are empty.
                if (!hasAllPermissions()) {
                    finish();
                }
                return;
            }
        }
    }

10-08 14:11