Monday, April 27, 2015

Android send SMS programmatically



An example for sending SMS programmatically in android. This will cost operator charges of sending sms. And also need to request sms sending permission from user to do this.

It also contents receiver for capture message sent and delivery status.
Following is the source for send SMS and get the status.



private void sendSMS(String phoneNumber, String message) {
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);
    PendingIntent deliveredIntent = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0);

    context.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, "SMS sent", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Sent SMS");
                    break;
                    
                default:
                    Log.i(TAG, "SMS sending failure");
                    Toast.makeText(context,"SMS sending failed",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(SENT));


    context.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, "SMS delivered", Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(context, "SMS not delivered", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentIntent, deliveredIntent);
}


To get the required permission add following code in to manifest file.
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

No comments:

Post a Comment