Android(安卓)发送短信
在 Android 中,您可以使用 SmsManager API 或设备内置的 SMS 应用程序发送 SMS。
在本教程中,我们向您展示了发送短信的两个基本实例:
- SmsManager API
- 内置 SMS 应用程序
当然,两者都需要 SEND_SMS 权限。除了上述方法, SmsManager 类中几乎没有其他重要函数可用。以下列出了这些方法:
| 编号 | 方法 & 描述 |
|---|---|
| 1 | ArrayList<String> divideMessage(String text) 此方法将消息文本分成几个片段,每个片段都不超过最大 SMS 消息大小。 |
| 2 | static SmsManager getDefault() 此方法用于获取 SmsManager 的默认实例 |
| 3 | void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) 此方法用于向特定应用程序端口发送基于数据的 SMS。 |
| 4 | void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) 发送多部分文本短信。 |
| 5 | void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent) 发送基于文本的短信。 |
实例
下面的实例实际演示了如何使用 SmsManager 对象向给定的手机号码发送 SMS。
为了实验这个例子,您需要实际的移动设备配备最新的 Android 操作系统,否则您使用模拟器可能会出现问题。
| 步骤 | 描述 |
|---|---|
| 1 | 您将使用 Android Studio IDE 创建一个 Android 应用程序,并将其命名为 com.example.demo 包下的 "My Application"。 |
| 2 | 修改 src/MainActivity.java 文件并添加所需代码以处理发送短信。 |
| 3 | 修改布局文件 res/layout/activity_main.xml 添加需要的 GUI 组件。我们添加了一个简单的 GUI,用于接收手机号码和发送短信的短信,以及一个发送短信的简单按钮。 |
| 4 | 无需在 res/values/strings.xml 中定义默认字符串常量Android工作室负责处理默认常量。 |
| 5 | 修改 AndroidManifest.xml |
| 6 | 运行应用程序以启动 Android 模拟器并验证应用程序中所做更改的结果。 |
以下是修改后的主活动文件的内容 src/com.example.deomo/MainActivity.java:
package com.example.demo;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;@Overrideprotected 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);}}}@Overridepublic 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 文件的内容:
<?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"><TextViewandroid: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" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="My Application "android:textColor="#ff87ff09"android:textSize="30dp"android:layout_below="@+id/textView1"android:layout_alignRight="@+id/imageButton"android:layout_alignEnd="@+id/imageButton" /><ImageButtonandroid: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" /><EditTextandroid: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" /><EditTextandroid: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" /><Buttonandroid: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 的内容,定义了常量:
<?xml version="1.0" encoding="utf-8"?><resources><string name="app_name">myapplication</string></resources>
下面是 AndroidManifest.xml 的内容:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.demo" ><uses-permission android:name="android.permission.SEND_SMS" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.demo.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>
让我们尝试运行 My Application 应用程序。假设您已经将实际的 Android 移动设备与计算机连接。要从 Android Studio 运行应用程序,请打开项目的 activity 文件之一,然后单击工具栏上的运行 Eclipse
图标。在启动应用程序之前,Android studio 安装程序将显示以下窗口,以选择要运行 Android 应用程序的选项。选择您的移动设备作为选项,然后检查将显示以下屏幕的移动设备:

现在,您可以输入所需的手机号码并在该号码上发送短信。最后,单击 Send SMS 按钮发送短信。确保您的 GSM/CDMA 连接正常,可以将短信发送给收件人。
你可以用逗号分隔一个短信号码,然后在你的程序中你必须将它们解析成一个数组字符串,最后你可以使用一个循环向所有给定的号码发送消息。这就是你如何编写自己的短信客户端。下一节将向您展示如何使用现有的 SMS 客户端发送 SMS。
使用内置 Intent 发送短信
您可以使用 Android Intent 通过调用 Android 的内置短信功能来发送短信。以下部分解释了发送 SMS 所需的 Intent 对象的不同部分。
Intent 对象 - 发送 SMS 的行为
您将使用 ACTION_VIEW 操作启动安装在 Android 设备上的 SMS 客户端。以下是使用 ACTION_VIEW 操作创建 Intent 意图的简单语法。
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
Intent 对象 - 发送短信的数据/类型
要发送 SMS,您需要使用 setData() 方法将 smsto: 指定为 URI,使用 setType() 方法指定数据类型将为 vnd.android-dir/mms-sms,如下所示:
smsIntent.setData(Uri.parse("smsto:"));smsIntent.setType("vnd.android-dir/mms-sms");
Intent 对象 - 附加数据发送短信
Android 内置支持添加电话号码和短信发送短信,如下所示:
smsIntent.putExtra("address" , new String("0123456789;3393993300"));smsIntent.putExtra("sms_body" , "Test SMS to Angilla");
这里,address 和 sms_body 区分大小写,只能用小写字符指定。您可以在单个字符串中指定多个数字,但用分号(;)分隔。
实例
下面的实例向您实际演示了如何使用 Intent 对象启动 SMS 客户端向给定的收件人发送 SMS。
为了实验这个例子,您需要实际的移动设备配备最新的 Android 操作系统,否则使用模拟器可能会出问题。
| 步骤 | 描述 |
|---|---|
| 1 | 您将使用Android studio IDE创建一个Android应用程序,并将其命名为 com.example.demo 包下的 My Application。 |
| 2 | 修改 src/MainActivity.java 文件并添加所需代码以处理发送短信。 |
| 3 | 修改布局文件 res/layout/activity_main.xml 添加 GUI 组件。我们添加了一个简单的按钮来启动 SMS 客户端。 |
| 4 | 无需定义默认常量。Android Studio 处理默认常量。 |
| 5 | 修改 AndroidManifest.xml |
| 6 | 运行应用程序以启动 Android 模拟器并验证应用程序中所做更改的结果。 |
以下是修改后的主活动文件的内容 src/com.example.demo/MainActivity.java:
package com.example.demo;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 {@Overrideprotected 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();}}@Overridepublic 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 文件:
<?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"><TextViewandroid: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" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="My Application "android:id="@+id/textView2"android:layout_below="@+id/textView"android:layout_centerHorizontal="true"android:textSize="30dp"android:textColor="#ff14be3c" /><ImageViewandroid: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" /><Buttonandroid: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 文件定义了常量:
<?xml version="1.0" encoding="utf-8"?><resources><string name="app_name">myapplication</string></resources>
下面是默认的 AndroidManifest.xml 文件:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.demo" ><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.demo.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>
让我们尝试运行 My Application 应用程序。假设您已经将实际的 Android 移动设备与计算机连接。要从 Android Studio 运行应用程序,请打开项目的 activity 文件之一,然后单击工具栏上的运行 Eclipse
图标。在启动应用程序之前,Android studio 安装程序将显示以下窗口,以选择要运行 Android 应用程序的选项。选择您的移动设备作为选项,然后检查将显示以下屏幕的移动设备:

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

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

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