Send sms permission doesn't work

前端 未结 7 464
南方客
南方客 2021-01-14 07:37

I want to send a simple message and i have in my manifest, but I always get: java.la

相关标签:
7条回答
  • 2021-01-14 08:20

    Try to use something like this. Not tested, but should work fine. Drop a note when you see some problem here.

    This is just to show how permission granting in Android M works. Please extend it by functionalities mentioned on Android tutorial site about permissions.

    You will need add ActivityCompat.shouldShowRequestPermissionRationale check to match best practices. I can extend this answer but I think it's not necessary. Just make sure you are granting permissions in runtime (or use targetSdkVersion lower then 23 - this is however not recommended)

    private static final int PERMISSION_SEND_SMS = 123;
    
    private void requestSmsPermission() {
    
        // check permission is given
        if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            // request permission (see result in onRequestPermissionsResult() method)
            ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.SEND_SMS},
                PERMISSION_SEND_SMS);
        } else {
            // permission already granted run sms send
            sendSms(phone, message);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
    
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted
                    sendSms(phone, message);
                } else {
                    // permission denied
                }
                return;
            }
        }
    }
    
    private void sendSms(String phoneNumber, String message){
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }
    
    0 讨论(0)
提交回复
热议问题