Wednesday, 22 July 2015

Send SMS from Android Application


Program to send SMS is very simple to develope. You hardly have to write two lines of code. For writing a code for sending SMS we need to understand SMSManager class

SMSManager

This class manages android SMS such as sending text, We need to create object by calling the static method.

android.telephony.SmsManager.getDefault();

This method will give you default instance of SmsManager .

Using this instance we need to call sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

scAddress - This is used to specify the SMS service center to use. If you enter null, the default service center for the device carrier will be used.
destinationAddress - is the target phone number you wish to text
text - message to be send

android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
smsManager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);


That's it, simple it is..

Permission

Another critical part is to update Androidmanifest.xml, by adding this code to it

 <uses-permission android:name="android.permission.SEND_SMS" />

This grants permission for Android application to send sms.

Code

EditText editText;
Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.editText1);
btnSend=(Button) findViewById(R.id.button1);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
}
});
}

No comments:

Post a Comment