Send SMS using Android code

By

January 23, 2013AndroidNo comments

In this tutorial we will learn how to send sms using android code.Android’s basic feature SMS is controlled by SMSManager of Telephony class.Using this we can send,receive short messages in the PDU formats.We have already seen the tutorial to send sms using way2sms and java.

Task: Creating a textarea that allows user to type messages and send to a number.

Create a new android project called SendSMS or any of your choice.Select the target version which is the min API level that application should compatible to.I chose android 4.0 Ice cream sandwich.

Layout

create a new screen layout file for the messaging interface.

activity_send_sms.XML



    

        

        
    

     

     

     

     


SendSms.Java

In this class file we will assign variables for the message and phone number textboxes and bind a onclicklistener for the send button.

package com.example.sendsms;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.telephony.SmsManager;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendSms extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_sms);
final EditText message = (EditText) findViewById(R.id.editText1);
final EditText sendto = (EditText) findViewById(R.id.editText2);
Button btnsend = (Button) findViewById(R.id.button1);
Button btnclear = (Button) findViewById(R.id.button2);
btnsend.setOnClickListener(new View.OnClickListener() {

	@Override
	public void onClick(View v) {
	// TODO Auto-generated method stub

       SmsManager sms = SmsManager.getDefault();
	sms.sendTextMessage(sendto.toString(), null, message.getText().toString(), null, null);
       //show toast message after sending
	Toast strmsg = Toast.makeText(SendSms.this,"Sending", Toast.LENGTH_SHORT);
	strmsg.show();

	  }

	});
		}
	});

btnclear.setOnClickListener(new View.OnClickListener() {

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	message.setText("");
	Toast strmsg = Toast.makeText(SendSms.this,"Cleared", Toast.LENGTH_SHORT);
	strmsg.show();

	}
});

}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_send_sms, menu);
return true;
	}
}

 

AndroidManifest.Xml

You need to get declare android.permission.SEND_SMS in the manifest file.

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

Screenshot

send message using code

SourceCode

Related posts:

Leave a Reply