Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
190 views

Android Sending SMS Tutorial

The document discusses two methods for sending SMS messages from an Android application: 1) Using the SmsManager API to send SMS messages programmatically 2) Using an Intent to launch the device's built-in SMS application It provides code examples for each method and describes additional SmsManager functions for dividing messages, retrieving the default SmsManager instance, and sending multipart or data messages. The document also includes an example Android application that uses the SmsManager API to send an SMS when a button is clicked.

Uploaded by

Justice Baloyi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
190 views

Android Sending SMS Tutorial

The document discusses two methods for sending SMS messages from an Android application: 1) Using the SmsManager API to send SMS messages programmatically 2) Using an Intent to launch the device's built-in SMS application It provides code examples for each method and describes additional SmsManager functions for dividing messages, retrieving the default SmsManager instance, and sending multipart or data messages. The document also includes an example Android application that uses the SmsManager API to send an SMS when a button is clicked.

Uploaded by

Justice Baloyi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

6/21/2016

AndroidSendingSMS

AndroidSendingSMS
Advertisements

PreviousPage

NextPage

InAndroid,youcanuseSmsManagerAPIordevicesBuiltinSMSapplicationtosendSMS's.
Inthistutorial,weshowsyoutwobasicexamplestosendSMSmessage
SmsManagerAPI
SmsManagersmsManager=SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo",null,"smsmessage",null,null

BuiltinSMSapplication
IntentsendIntent=newIntent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body","defaultcontent");
sendIntent.setType("vnd.androiddir/mmssms");
startActivity(sendIntent);

Ofcourse,bothneedSEND_SMSpermission.
<usespermissionandroid:name="android.permission.SEND_SMS"/>

Apart from the above method, there are few other important functions available in
SmsManagerclass.Thesemethodsarelistedbelow
Sr.No.

Method&Description

ArrayList<String>divideMessage(Stringtext)

This method divides a message text into several


fragments, none bigger than the maximum SMS
messagesize.
2

staticSmsManagergetDefault()

This method is used to get the default instance of


theSmsManager
3

voidsendDataMessage(StringdestinationAddress,
StringscAddress,shortdestinationPort,byte[]
data,PendingIntentsentIntent,PendingIntent
deliveryIntent)

ThismethodisusedtosendadatabasedSMStoa
specificapplicationport.
4

voidsendMultipartTextMessage(String
destinationAddress,StringscAddress,

http://www.tutorialspoint.com/android/android_sending_sms.htm

1/10

6/21/2016

AndroidSendingSMS

ArrayList<String>parts,
ArrayList<PendingIntent>sentIntents,
ArrayList<PendingIntent>deliveryIntents)

SendamultiparttextbasedSMS.
5

voidsendTextMessage(StringdestinationAddress,
StringscAddress,Stringtext,PendingIntent
sentIntent,PendingIntentdeliveryIntent)

SendatextbasedSMS.

Example
FollowingexampleshowsyouinpracticalhowtouseSmsManagerobjecttosendanSMSto
thegivenmobilenumber.
Toexperimentwiththisexample,youwillneedactualMobiledeviceequippedwith
latestAndroidOS,otherwiseyouwillhavetostrugglewithemulatorwhichmaynot
work.
Step

Description

YouwilluseAndroidStudioIDEtocreateanAndroid
applicationandnameitastutorialspointundera
packagecom.example.tutorialspoint.Whilecreatingthis
project,makesureyouTargetSDKandCompileWithat
thelatestversionofAndroidSDKtousehigherlevelsof
APIs.

Modifysrc/MainActivity.javafileandaddrequiredcodeto
takecareofsendingemail.

ModifylayoutXMLfileres/layout/activity_main.xmladd
anyGUIcomponentifrequired.I'maddingasimpleGUI
totakemobilenumberandSMStexttobesentanda
simplebuttontosendSMS.

Noneedtodefinedefaultstringconstantsat
res/values/strings.xml.Androidstudiotakescareof
defaultconstants.

ModifyAndroidManifest.xmlasshownbelow

RuntheapplicationtolaunchAndroidemulatorandverify
theresultofthechangesdoneintheapplication.

Following

is

the

content

of

the

modified

main

activity

filesrc/com.example.tutorialspoint/MainActivity.java.
packagecom.example.tutorialspoint;
http://www.tutorialspoint.com/android/android_sending_sms.htm

2/10

6/21/2016

AndroidSendingSMS

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.telephony.SmsManager;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity{
ButtonsendBtn;
EditTexttxtphoneNo;
EditTexttxtMessage;

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn=(Button)findViewById(R.id.btnSendSMS);
txtphoneNo=(EditText)findViewById(R.id.editText);
txtMessage=(EditText)findViewById(R.id.editText2);
sendBtn.setOnClickListener(newView.OnClickListener(){
publicvoidonClick(Viewview){
sendSMSMessage();
}
});
}
protectedvoidsendSMSMessage(){
Log.i("SendSMS","");
StringphoneNo=txtphoneNo.getText().toString();
Stringmessage=txtMessage.getText().toString();

try{
SmsManagersmsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message,null,null
Toast.makeText(getApplicationContext(),"SMSsent.",Toast.
}

catch(Exceptione){
Toast.makeText(getApplicationContext(),"SMSfaild,pleasetryagain."
e.printStackTrace();
}
}

@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}

Followingwillbethecontentofres/layout/activity_main.xmlfile:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
http://www.tutorialspoint.com/android/android_sending_sms.htm

3/10

6/21/2016

AndroidSendingSMS

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SendingSMSExample"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"/>

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"/>

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="EnterPhoneNumber"
android:phoneNumber="true"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"
android:hint="EnterSMS"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SendSms"
android:id="@+id/btnSendSMS"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"/>
</RelativeLayout>
http://www.tutorialspoint.com/android/android_sending_sms.htm

4/10

6/21/2016

AndroidSendingSMS

Followingwillbethecontentofres/values/strings.xmltodefinetwonewconstants
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<stringname="app_name">tutorialspoint</string>
<stringname="action_settings">Settings</string>
</resources>

FollowingisthedefaultcontentofAndroidManifest.xml:
<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint"
android:versionCode="1"
android:versionName="1.0">

<usessdk
android:minSdkVersion="8"
android:targetSdkVersion="22"/>
<usespermissionandroid:name="android.permission.SEND_SMS"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name">

<intentfilter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"
</intentfilter>

</activity>

</application>
</manifest>

Let'strytorunyourtutorialspointapplication. I assume you have connected your actual


AndroidMobiledevicewithyourcomputer.ToruntheappfromAndroidstudio,openoneof
yourproject'sactivityfilesandclickRun
icon from the toolbar. Before starting your application, Android studio installer will display
followingwindowtoselectanoptionwhereyouwanttorunyourAndroidapplication.

http://www.tutorialspoint.com/android/android_sending_sms.htm

5/10

6/21/2016

AndroidSendingSMS

Nowyoucanenteradesiredmobilenumberandatextmessagetobesentonthatnumber.
FinallyclickonSendSMSbuttontosendyourSMS.MakesureyourGSM/CDMAconnection
isworkingfinetodeliveryourSMStoitsrecipient.
YoucantakeanumberofSMSseparatedbycommaandtheninsideyourprogramyouwill
havetoparsethemintoanarraystringandfinallyyoucanusealooptosendmessagetoall
the given numbers. That's how you can write your own SMS client. Next section will show
youhowtouseexistingSMSclienttosendSMS.

UsingBuiltinIntenttosendSMS
YoucanuseAndroidIntenttosendSMSbycallingbuiltinSMSfunctionalityoftheAndroid.
FollowingsectionexplainsdifferentpartsofourIntentobjectrequiredtosendanSMS.

IntentObjectActiontosendSMS
YouwilluseACTION_VIEWactiontolaunchanSMSclientinstalledonyourAndroiddevice.
FollowingissimplesyntaxtocreateanintentwithACTION_VIEWaction
IntentsmsIntent=newIntent(Intent.ACTION_VIEW);

IntentObjectData/TypetosendSMS
TosendanSMSyouneedtospecifysmsto:asURIusingsetData()methodanddatatype
willbetovnd.androiddir/mmssmsusingsetType()methodasfollows

http://www.tutorialspoint.com/android/android_sending_sms.htm

6/10

6/21/2016

AndroidSendingSMS

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.androiddir/mmssms");

IntentObjectExtratosendSMS
Android has builtin support to add phone number and text message to send an SMS as
follows
smsIntent.putExtra("address",newString("0123456789;3393993300"));
smsIntent.putExtra("sms_body","TestSMStoAngilla");

Hereaddressandsms_bodyarecasesensitiveandshouldbespecifiedinsmall
charactersonly.Youcanspecifymorethanonenumberinsinglestringbutseparated
bysemicolon().

Example
FollowingexampleshowsyouinpracticalhowtouseIntentobjecttolaunchSMSclientto
sendanSMStothegivenrecipients.
Toexperimentwiththisexample,youwillneedactualMobiledeviceequippedwith
latestAndroidOS,otherwiseyouwillhavetostrugglewithemulatorwhichmaynot
work.
Step

Description

YouwilluseAndroidstudioIDEtocreateanAndroid
applicationandnameitastutorialspointundera
packagecom.example.tutorialspoint.Whilecreatingthis
project,makesureyouTargetSDKandCompileWithat
thelatestversionofAndroidSDKtousehigherlevelsof
APIs.

Modifysrc/MainActivity.javafileandaddrequiredcodeto
takecareofsendingSMS.

ModifylayoutXMLfileres/layout/activity_main.xmladd
anyGUIcomponentifrequired.I'maddingasimple
buttontolaunchSMSClient.

Noneedtodefinedefaultconstants.Androidstudiotakes
careofdefaultconstants.

ModifyAndroidManifest.xmlasshownbelow

RuntheapplicationtolaunchAndroidemulatorandverify
theresultofthechangesdoneintheapplication.

Following

is

the

content

http://www.tutorialspoint.com/android/android_sending_sms.htm

of

the

modified

main

activity
7/10

6/21/2016

AndroidSendingSMS

filesrc/com.example.tutorialspoint/MainActivity.java.
packagecom.example.tutorialspoint;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonstartBtn=(Button)findViewById(R.id.button);
startBtn.setOnClickListener(newView.OnClickListener(){
publicvoidonClick(Viewview){
sendSMS();
}
});
}

protectedvoidsendSMS(){
Log.i("SendSMS","");
IntentsmsIntent=newIntent(Intent.ACTION_VIEW);

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.androiddir/mmssms");
smsIntent.putExtra("address",newString("01234"));
smsIntent.putExtra("sms_body","Test");

try{
startActivity(smsIntent);
finish();
Log.i("FinishedsendingSMS...","");
}
catch(android.content.ActivityNotFoundExceptionex){
Toast.makeText(MainActivity.this,
"SMSfaild,pleasetryagainlater.",Toast.LENGTH_SHORT).show
}
}

@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}

Followingwillbethecontentofres/layout/activity_main.xmlfile
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
http://www.tutorialspoint.com/android/android_sending_sms.htm

8/10

6/21/2016

AndroidSendingSMS

android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DragandDropExample"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TutorialsPoint"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c"/>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ComposeSMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"/>

</RelativeLayout>

Followingwillbethecontentofres/values/strings.xmltodefinetwonewconstants
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<stringname="app_name">tutorialspoint</string>
<stringname="action_settings">Settings</string>
</resources>

FollowingisthedefaultcontentofAndroidManifest.xml
<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint"
android:versionCode="1"
http://www.tutorialspoint.com/android/android_sending_sms.htm

9/10

6/21/2016

AndroidSendingSMS

android:versionName="1.0">

<usessdk
android:minSdkVersion="8"
android:targetSdkVersion="22"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">

<activity
android:name

http://www.tutorialspoint.com/android/android_sending_sms.htm

10/10

You might also like