Sie sind auf Seite 1von 9

9/10/2016

AndroidSendingSMS

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

Copyrighttutorialspoint.com

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"/>

Apartfromtheabovemethod,therearefewotherimportantfunctionsavailableinSmsManagerclass.Thesemethodsarelistedbelow

Sr.No.

Method&Description

ArrayList<String>divideMessageS tringtext
Thismethoddividesamessagetextintoseveralfragments,nonebiggerthanthemaximumSMSmessagesize.

staticSmsManagergetDefault
ThismethodisusedtogetthedefaultinstanceoftheSmsManager

voidsendDataMessage
S tringdestinationAddress, S tringscAddress, shortdestinationP ort, byte[]data, P endingI ntentsentI ntent, P endingI ntentdeliveryI ntent

ThismethodisusedtosendadatabasedSMStoaspecificapplicationport.
4

voidsendMultipartTextMessage
S tringdestinationAddress, S tringscAddress, ArrayList < S tring > parts, ArrayList < P endingI ntent > sentI ntents, ArrayList
< P endingI ntent > deliveryI ntents

SendamultiparttextbasedSMS.
5

voidsendTextMessageS tringdestinationAddress, S tringscAddress, S tringtext, P endingI ntentsentI ntent, P endingI ntentdeliveryI ntent
SendatextbasedSMS.

Example
FollowingexampleshowsyouinpracticalhowtouseSmsManagerobjecttosendanSMStothegivenmobilenumber.

Toexperimentwiththisexample,youwillneedactualMobiledeviceequippedwithlatestAndroidOS,otherwiseyouwillhavetostrugglewithemulator
whichmaynotwork.

Step

Description

YouwilluseAndroidStudioIDEtocreateanAndroidapplicationandnameitastutorialspointunderapackagecom.example.tutorialspoint.Whilecreatingthis
project,makesureyouTargetSDKandCompileWithatthelatestversionofAndroidSDKtousehigherlevelsofAPIs.

Modifysrc/MainActivity.javafileandaddrequiredcodetotakecareofsendingemail.

ModifylayoutXMLfileres/layout/activity_main.xmladdanyGUIcomponentifrequired.I'maddingasimpleGUItotakemobilenumberandSMStexttobe

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/9

9/10/2016

AndroidSendingSMS

sentandasimplebuttontosendSMS.
4

Noneedtodefinedefaultstringconstantsatres/values/strings.xml.Androidstudiotakescareofdefaultconstants.

ModifyAndroidManifest.xmlasshownbelow

RuntheapplicationtolaunchAndroidemulatorandverifytheresultofthechangesdoneintheapplication.

Followingisthecontentofthemodifiedmainactivityfilesrc/com.example.tutorialspoint/MainActivity.java.
packagecom.example.tutorialspoint;
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.LENGTH_LONG).show();
}

catch(Exceptione){
Toast.makeText(getApplicationContext(),"SMSfaild,pleasetryagain.",Toast.LENGTH_LONG).show();
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"
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"

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/9

9/10/2016

AndroidSendingSMS

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>

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">

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/9

9/10/2016

AndroidSendingSMS

<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.IassumeyouhaveconnectedyouractualAndroidMobiledevicewithyourcomputer.ToruntheappfromAndroidstudio,
openoneofyourproject'sactivityfilesandclickRun
iconfromthetoolbar.Beforestartingyourapplication,AndroidstudioinstallerwilldisplayfollowingwindowtoselectanoptionwhereyouwanttorunyourAndroid
application.

Nowyoucanenteradesiredmobilenumberandatextmessagetobesentonthatnumber.FinallyclickonSendSMSbuttontosendyourSMS.Makesureyour
GSM/CDMAconnectionisworkingfinetodeliveryourSMStoitsrecipient.
YoucantakeanumberofSMSseparatedbycommaandtheninsideyourprogramyouwillhavetoparsethemintoanarraystringandfinallyyoucanusealooptosend
messagetoallthegivennumbers.That'showyoucanwriteyourownSMSclient.NextsectionwillshowyouhowtouseexistingSMSclienttosendSMS.

UsingBuiltinIntenttosendSMS
YoucanuseAndroidIntenttosendSMSbycallingbuiltinSMSfunctionalityoftheAndroid.FollowingsectionexplainsdifferentpartsofourIntentobjectrequiredtosend
anSMS.

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

IntentObjectData/TypetosendSMS
TosendanSMSyouneedtospecifysmsto:asURIusingsetDatamethodanddatatypewillbetovnd.androiddir/mmssmsusingsetTypemethodasfollows
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.androiddir/mmssms");

IntentObjectExtratosendSMS
AndroidhasbuiltinsupporttoaddphonenumberandtextmessagetosendanSMSasfollows

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/9

9/10/2016

AndroidSendingSMS

smsIntent.putExtra("address",newString("0123456789;3393993300"));
smsIntent.putExtra("sms_body","TestSMStoAngilla");

Hereaddressandsms_bodyarecasesensitiveandshouldbespecifiedinsmallcharactersonly.Youcanspecifymorethanonenumberinsinglestringbut
separatedbysemicolon;.

Example
FollowingexampleshowsyouinpracticalhowtouseIntentobjecttolaunchSMSclienttosendanSMStothegivenrecipients.

Toexperimentwiththisexample,youwillneedactualMobiledeviceequippedwithlatestAndroidOS,otherwiseyouwillhavetostrugglewithemulator
whichmaynotwork.

Step

Description

YouwilluseAndroidstudioIDEtocreateanAndroidapplicationandnameitastutorialspointunderapackagecom.example.tutorialspoint.Whilecreatingthis
project,makesureyouTargetSDKandCompileWithatthelatestversionofAndroidSDKtousehigherlevelsofAPIs.

Modifysrc/MainActivity.javafileandaddrequiredcodetotakecareofsendingSMS.

ModifylayoutXMLfileres/layout/activity_main.xmladdanyGUIcomponentifrequired.I'maddingasimplebuttontolaunchSMSClient.

Noneedtodefinedefaultconstants.Androidstudiotakescareofdefaultconstants.

ModifyAndroidManifest.xmlasshownbelow

RuntheapplicationtolaunchAndroidemulatorandverifytheresultofthechangesdoneintheapplication.

Followingisthecontentofthemodifiedmainactivityfilesrc/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();
}

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/9

9/10/2016

AndroidSendingSMS

@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: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"
android:versionName="1.0">

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/9

9/10/2016

AndroidSendingSMS

<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.IassumeyouhaveconnectedyouractualAndroidMobiledevicewithyourcomputer.ToruntheappfromAndroidstudio,
openoneofyourproject'sactivityfilesandclickRun
iconfromthetoolbar.Beforestartingyourapplication,AndroidstudiowilldisplayfollowingwindowtoselectanoptionwhereyouwanttorunyourAndroidapplication.

Selectyourmobiledeviceasanoptionandthencheckyourmobiledevicewhichwilldisplayfollowingscreen:

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/9

9/10/2016

AndroidSendingSMS

NowuseComposeSMSbuttontolaunchAndroidbuiltinSMSclientswhichisshownbelow:

http://www.tutorialspoint.com/cgibin/printpage.cgi

8/9

9/10/2016

AndroidSendingSMS

YoucanmodifyeitherofthegivendefaultfieldsandfinallyusesendSMSbuttontosendyourSMStothementionedrecipient.

http://www.tutorialspoint.com/cgibin/printpage.cgi

9/9

Das könnte Ihnen auch gefallen