Android 简明教程

Android - Sending SMS

在 Android 系统中,你可以使用 SmsManager API 或设备内置的 SMS 应用发送短信。在本教程中,我们向你展示了两个发送短信消息的基本示例:

In Android, you can use SmsManager API or devices Built-in SMS application to send SMS’s. In this tutorial, we shows you two basic examples to send SMS message −

SmsManager API

SmsManager API

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Built-in SMS application

Built-in SMS application

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

当然,两者都需要 SEND_SMS permission

Of course, both need SEND_SMS permission.

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

除了上述方法之外,SmsManager 类中还提供其他一些重要函数。下面列出了这些方法:

Apart from the above method, there are few other important functions available in SmsManager class. These methods are listed below −

Sr.No.

Method & Description

1

ArrayList<String> divideMessage(String text) This method divides a message text into several fragments, none bigger than the maximum SMS message size.

2

static SmsManager getDefault() This method is used to get the default instance of the SmsManager

3

void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) This method is used to send a data based SMS to a specific application port.

4

void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) Send a multi-part text based SMS.

5

void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent) Send a text based SMS.

Example

以下示例以实际方式向您展示如何使用 SmsManager 对象向给定的移动电话号码发送短信。

Following example shows you in practical how to use SmsManager object to send an SMS to the given mobile number.

Step

Description

1

You will use Android Studio IDE to create an Android application and name it as tutorialspoint under a package com.example.tutorialspoint.

2

Modify src/MainActivity.java file and add required code to take care of sending sms.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple GUI to take mobile number and SMS text to be sent and a simple button to send SMS.

4

No need to define default string constants at res/values/strings.xml. Android studio takes care of default constants.

5

Modify AndroidManifest.xml as shown below

6

Run the application to launch Android emulator and verify the result of the changes done in the application.

以下是修改后的主活动文件 src/com.example.tutorialspoint/MainActivity.java 的内容。

Following is the content of the modified main activity file src/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;

import android.util.Log;
import android.view.Menu;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
   private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
   Button sendBtn;
   EditText txtphoneNo;
   EditText txtMessage;
   String phoneNo;
   String message;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      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(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMSMessage();
         }
      });
   }

   protected void sendSMSMessage() {
      phoneNo = txtphoneNo.getText().toString();
      message = txtMessage.getText().toString();

      if (ContextCompat.checkSelfPermission(this,
         Manifest.permission.SEND_SMS)
         != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
               Manifest.permission.SEND_SMS)) {
            } else {
               ActivityCompat.requestPermissions(this,
                  new String[]{Manifest.permission.SEND_SMS},
                  MY_PERMISSIONS_REQUEST_SEND_SMS);
            }
      }
   }

   @Override
   public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
      switch (requestCode) {
         case MY_PERMISSIONS_REQUEST_SEND_SMS: {
            if (grantResults.length > 0
               && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  SmsManager smsManager = SmsManager.getDefault();
                  smsManager.sendTextMessage(phoneNo, null, message, null, null);
                  Toast.makeText(getApplicationContext(), "SMS sent.",
                     Toast.LENGTH_LONG).show();
            } else {
               Toast.makeText(getApplicationContext(),
                  "SMS faild, please try again.", Toast.LENGTH_LONG).show();
               return;
            }
         }
      }

   }
}

以下是 res/layout/activity_main.xml 文件的内容——

Following will be the content of res/layout/activity_main.xml file −

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns: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"
      android:layout_height="wrap_content"
      android:text="Sending SMS Example"
      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="Tutorials point "
      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="Enter Phone Number"
      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="Enter SMS" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Send Sms"
      android:id="@+id/btnSendSMS"
      android:layout_below="@+id/editText2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp" />

</RelativeLayout>

以下是 res/values/strings.xml 的内容,用于定义两个新常量——

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
</resources>

以下是 AndroidManifest.xml 的默认内容−

Following is the default content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint" >

   <uses-permission android: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" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>

让我们尝试运行您的 tutorialspoint 应用程序。我假设您已将实际的 Android 移动设备连接到电脑。要从 Android Studio 运行应用,请打开您项目的其中一个活动文件,然后从工具栏中单击运行图标。在启动应用程序之前,Android Studio 安装程序将显示以下窗口,以便选择您要在其上运行 Android 应用程序的选项。

Let’s try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.

android mobile devices

现在,您可以输入要发送到该号码的所需移动号码和文本消息。最后,单击 Send SMS 按钮以发送您的短信。确保您的 GSM/CDMA 连接工作正常,以便将您的短信发送给收件人。

Now you can enter a desired mobile number and a text message to be sent on that number. Finally click on Send SMS button to send your SMS. Make sure your GSM/CDMA connection is working fine to deliver your SMS to its recipient.

您可以获取多个用逗号分隔的短信,然后在程序内部将它们解析成一个数组字符串,最后您可以使用一个循环向所有给定的号码发送消息。这就是编写您自己的短信客户端的方法。下一节将向您展示如何使用现有的短信客户端来发送短信。

You can take a number of SMS separated by comma and then inside your program you will have to parse them into an array string and finally you can use a loop to send message to all the given numbers. That’s how you can write your own SMS client. Next section will show you how to use existing SMS client to send SMS.

Using Built-in Intent to send SMS

您可以使用 Android Intent 来发送短信,方法是调用 Android 的内置短信功能。以下部分说明了发送短信所需的 Intent 对象的不同部分。

You can use Android Intent to send SMS by calling built-in SMS functionality of the Android. Following section explains different parts of our Intent object required to send an SMS.

Intent Object - Action to send SMS

您将使用 ACTION_VIEW 操作来启动已安装在您的 Android 设备上的短信客户端。以下是创建具有 ACTION_VIEW 操作的 intent 的简单语法。

You will use ACTION_VIEW action to launch an SMS client installed on your Android device. Following is simple syntax to create an intent with ACTION_VIEW action.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object - Data/Type to send SMS

要发送短信,您需要使用 setData() 方法将 smsto: 指定为 URI,并使用 setType() 方法将数据类型指定为 vnd.android-dir/mms-sms ,如下所示:

To send an SMS you need to specify smsto: as URI using setData() method and data type will be to vnd.android-dir/mms-sms using setType() method as follows −

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS

Android 内置支持,可将电话号码和文本消息添加到短信中,如下所示:

Android has built-in support to add phone number and text message to send an SMS as follows −

smsIntent.putExtra("address"  , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body"  , "Test SMS to Angilla");

Example

以下示例向您实际演示如何使用 Intent 对象启动短信客户端来向给定收件人发送短信。

Following example shows you in practical how to use Intent object to launch SMS client to send an SMS to the given recipients.

Step

Description

1

You will use Android studio IDE to create an Android application and name it as tutorialspoint under a package com.example.tutorialspoint.

2

Modify src/MainActivity.java file and add required code to take care of sending SMS.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I’m adding a simple button to launch SMS Client.

4

No need to define default constants.Android studio takes care of default constants.

5

Modify AndroidManifest.xml as shown below

6

Run the application to launch Android emulator and verify the result of the changes done in the application.

以下是修改后的主活动文件 src/com.example.tutorialspoint/MainActivity.java 的内容。

Following is the content of the modified main activity file src/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Button startBtn = (Button) findViewById(R.id.button);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMS();
         }
      });
   }

   protected void sendSMS() {
      Log.i("Send SMS", "");
      Intent smsIntent = new Intent(Intent.ACTION_VIEW);

      smsIntent.setData(Uri.parse("smsto:"));
      smsIntent.setType("vnd.android-dir/mms-sms");
      smsIntent.putExtra("address"  , new String ("01234"));
      smsIntent.putExtra("sms_body"  , "Test ");

      try {
         startActivity(smsIntent);
         finish();
         Log.i("Finished sending SMS...", "");
      } catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this,
         "SMS faild, please try again later.", Toast.LENGTH_SHORT).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.main, menu);
      return true;
   }
}

以下是 res/layout/activity_main.xml 文件的内容——

Following will be the content of res/layout/activity_main.xml file −

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns: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="Drag and Drop Example"
      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="Tutorials Point "
      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="Compose SMS"
      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>

以下是 res/values/strings.xml 的内容,用于定义两个新常量——

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
</resources>

以下是 AndroidManifest.xml 的默认内容−

Following is the default content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint" >

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

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>

让我们尝试运行您的 tutorialspoint 应用程序。我假设您已将实际 Android 移动设备连接到计算机。要从 Android Studio 运行该应用,请打开项目的某个活动文件并单击工具栏中的运行图标。在启动应用程序之前,Android Studio 将显示以下窗口,供您选择运行 Android 应用程序的位置。

Let’s try to run your tutorialspoint application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.

android mobile device1

选择你的移动设备作为选项,然后检查你的移动设备,它将显示以下屏幕 −

Select your mobile device as an option and then check your mobile device which will display following screen −

mobile sms compose

现在,使用 Compose SMS 按钮启动 Android 内置短信客户端,如下所示 −

Now use Compose SMS button to launch Android built-in SMS clients which is shown below −

mobile sms screen

您可以修改任一给定的默认字段,最后使用发送短信按钮向提到的收件人发送短信。

You can modify either of the given default fields and finally use send SMS button to send your SMS to the mentioned recipient.