Sunday 24 December 2017

Handling Permission and Sending SMS

SMS sending and receiving is simple but due to advancements in permissions since Marshmallow version it needs special permission(s) to be requested runtime. Then user may or may not grant these permission(s). Earlier versions do not require permission(s) on app launch or at runtime.  Therefore, we need to take care of permission(s), depending on the version of the phone.

To request permission, we define method in the main activity as follow:

public class MainActivity extends AppCompatActivity {

@Overrideprotected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestSMSPermission();

    if(isSMSPermitted()){
         //Get the default instance of SmsManager         
         SmsManager smsManager = SmsManager.getDefault();
         String mobileNumber = "92xxxxxxxx"; //enter mobile number
         String smsBody = " Hi, this is a test SMS, Cheers!";
         short port = 6734;
         //Send a text SMS
         SmsManager.getDefault().sendTextMessage(phoneNumber, null, smsBody, null, null);
    }
}

/** * Request SMS permission runtime */private void requestSMSPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
            Manifest.permission.READ_SMS)) {

        //https://developer.android.com/training/permissions/requesting.html    }
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},
            SMS_PERMISSION_REQ_CODE);
  }

  //Handle Permission Result 
  @Override 
  public void onRequestPermissionsResult(int requestCode,
                                        String permissions[], int[] results) {

     switch (requestCode) {

         case SMS_PERMISSION_REQ_CODE: {

             if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) {

                 // permission granted
                 Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();

             } else {

                 // permission denied
                 Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
             }
             return;
           }
        }
    }
   /** * Check if SMS permission granted */
   public boolean isSMSPermitted() {

    return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
  }
}




No comments:

Post a Comment