Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know Sms Sending is blocked by permission check?

Tags:

android

sms

Here blow is the code:

SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(target, null, content, sentPI, delieveredPI);

I have declared using permission of "android.permission.SEND_SMS" in AndroidManifest.xml.
But on some phones, when sending sms with api, a dialog asking for permission pops up, and if user choose "Not grant" the permission, the sms sending will fail silently, without any callback or broadcast.
Question is: Is there any method to detect this kind of blocking?

like image 409
ZhangYu Avatar asked Dec 22 '25 03:12

ZhangYu


1 Answers

But on some phones, when sending sms with api, a dialog asking for permission pops up

Yes, this will happen on Android Marshmallow devices that has a new runtime permission model.

You need to use the checkSelfPermission method before you try and use this permission, as such:

if (Context.checkSelfPermission(Manifest.permission.SEND_SMS)
                                  != PackageManager.PERMISSION_GRANTED) {
   // permission is not granted, ask for permission:
   requestPermissions(this, //assuming this is Activity or a subclass of it
            new String[] { Manifest.permission.SEND_SMS},
            MY_KEY_FOR_RETURNED_VALUE);
 }

Optionally, you could (and should) also display a rationale to the user (first checking if Android will even ask the user for that permission using shouldShowRequestPermissionRationale - the user won't be prompted if, for example, he denied and marked "don't ask me again" so you should check first and not always display).

Then check the request answer in your implementation of onRequestPermissionsResult:

@override
public void onRequestPermissionsResult(int requestCode,
    String permissions[], int[] grantResults) {

    if (requestCode == MY_KEY_FOR_RETURNED_VALUE) {
       if (grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

           // permission is granted
       }
    }

You can find more information either here or in the official documentation here.

like image 141
Ori Lentz Avatar answered Dec 23 '25 19:12

Ori Lentz