In this chapter, we will explain you how to send a SMS in android using a Built-in SMS App or SmsManager. The application is simple and easy to build. SmsManager class handles the SMS process. To send an SMS, you should get an instance of SmsManager class and add permission to SEND_SMS in the Android manifest file. The following examples illustrate how to send an SMS.Using SmsManager:
It’s like a custom SMS.
SmsManager manages SMS operations such as sending data, text, and pdu SMS messages. You can get this object by calling the static method getDefault(). This class has many methods, such as:
•divideMessage(String text): Divide a message text into several fragments, none bigger than the maximum SMS message size. •sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent): Send a text based SMS.
•sendMultimediaMessage(Context context, Uri contentUri, String locationUrl, Bundle configOverrides, PendingIntent sentIntent): Send an MMS message
•downloadMultimediaMessage(Context context, String locationUrl, Uri contentUri, Bundle configOverrides, PendingIntent downloadedIntent): Download an MMS message from carrier by a given location URL.
Example:
The following example illustrates the use of SmsManager.
Create MainActivity.java under src/<your packagename>
MainActivity.java:
[java]
public class MainActivity extends Activity {
Context context;
Button send;
EditText phnum,sms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by Id
Button send=(Button)findViewById(R.id.button1);
phnum=(EditText)findViewById(R.id.editText1);
sms=(EditText)findViewById(R.id.editText2);
context=this;
//onclick send
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendSMSMessage();
//open in built app
/*Intent i = new Intent(Intent.ACTION_VIEW);
i.putExtra("sms_body", "text to send");
i.setType("vnd.android-dir/mms-sms");
startActivity(i);*/
}
});
}
protected void sendSMSMessage() {
String phoneNo = phnum.getText().toString();
String message = sms.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",oast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "please try again.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
[/java]
Create activity_main.xml under res/layout folder.
activity_main.xml:
[code lang="xml"]
[/code]
AndroidManifest.xml:
[code lang="xml"]
[/code]
Output: