Android - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android Send SMS

Android Send SMS

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 smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNum", null, "message", null, null);
Using Built-in App: It is using an Intent.
Intent i = new Intent(Intent.ACTION_VIEW);
i.putExtra("sms_body", "text to send");
i.setType("vnd.android-dir/mms-sms");
startActivity(i);
You need to declare SMS_SEND permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.SEND_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: 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"]