您好!欢迎来到源码码网

Android实现发送短信和接受短信功能

  • 源码教程
  • 来源:源码码网
  • 编辑:admin
  • 时间:2021-01-13 17:21
  • 阅读:729

在学接收短信和发送短信之前,先简单介绍一下 SMS 短消息服务。

SMS(Short Message Service,短信息服务)是一种存储和转发服务。也就是说,短信息并不是直接从发信人发送到接收人,而是始终通过 SMS 中心进行转发。如果接收人处于未连接状态(可能电话已关闭),那么信息将在接收人再次连接时发送。

接收短信

要使 Android 应用程序能够接收短信息,需要以下三个步骤:

1)Android 应用程序必须具有接收 SMS 短信息的权限,在 AndroidManifest.xml 文件中配置如下:

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


2)Android 应用程序需要定义一个 BroadcastReceiver 的子类,并通过重载其 public void onReceive(Context arg0, Intent arg1) 方法来处理接收到短信息的事件。

3)在 AndroidManifest.xml 文件中对 BroadcastReceiver 子类的 <intent-filter> 属性进行配置,使其能够获取短信息接收 Action。配置如下:

<intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED"
</intent-filter>

接收短信实例

实例 receiveMessageDemo 演示了接收短信并提示的过程,运行效果如图 1 所示。

receiveMessageDemo实例

图 1  receiveMessageDemo实例

其 layout 文件 main.xml 的代码如下:


  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="fill_parent"

  4. android:layout_height="fill_parent"

  5. android:orientation="vertical">


  6. <EditText

  7. android:id="@+id/editText1"

  8. android:layout_width="match_parent"

  9. android:layout_height="wrap_content" />


  10. <requestFocus />

  11. </LinearLayout>


AndroidManifest.xml 文件的代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  3. package="introduction.android.receivemessagedemo"

  4. android:versionCode="1"

  5. android:versionName="1.0">


  6. <uses-sdk android:minSdkVersion="14" />

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

  8. <application

  9. android:allowBackup="true"

  10. android:icon="@mipmap/ic_launcher"

  11. android:label="@string/app_name"

  12. android:roundIcon="@mipmap/ic_launcher_round"

  13. android:supportsRtl="true"

  14. android:theme="@style/AppTheme">

  15. <activity android:name=".MainActivity">

  16. <intent-filter>

  17. <action android:name="android.intent.action.MAIN" />

  18. <category android:name="android.intent.category.LAUNCHER" />

  19. </intent-filter>

  20. </activity>

  21. <receiver android:name="SmsReceiver">

  22. <intent-filter>

  23. <action android:name="android.provider.Telephony.SMS_RECEIVED" />

  24. </intent-filter>

  25. </receiver>

  26. </application>


  27. </manifest>


MainActivity.java 的代码如下:

  1. package introduction.android.receivemessagedemo;


  2. import android.support.v7.app.AppCompatActivity;

  3. import android.os.Bundle;

  4. import android.widget.EditText;


  5. public class MainActivity extends AppCompatActivity {


  6. @Override

  7. protected void onCreate(Bundle savedInstanceState) {

  8. super.onCreate(savedInstanceState);

  9. setContentView(R.layout.activity_main);

  10. EditText text = (EditText) this.findViewById(R.id.editText1);

  11. text.setText("waiting.....");

  12. }

  13. }

Intent 广播接收器定义为 SmsReceiver,用于对接收到短信息的事件进行处理。

SmsReceiver. Java
 的代码如下:

  1. package introduction.android.receivemessagedemo;


  2. import android.content.BroadcastReceiver;

  3. import android.content.Context;

  4. import android.content.Intent;

  5. import android.os.Bundle;

  6. import android.telephony.SmsMessage;

  7. import android.widget.Toast;


  8. /**

  9. * Created ymama.net on 2019/4/10.

  10. */


  11. public class SmsReceiver extends BroadcastReceiver {

  12. StringBuilder strb = new StringBuilder();


  13. @Override

  14. public void onReceive(Context arg0, Intent arg1) {

  15. Bundle bundle = arg1.getExtras();

  16. Object[] pdus = (Object[]) bundle.get("pdus");

  17. SmsMessage[] msgs = new SmsMessage[pdus.length];

  18. for (int i = 0; i < pdus.length; i++) {

  19. msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

  20. }

  21. for (SmsMessage msg : msgs) {

  22. strb.append("发信人: ");

  23. strb.append(msg.getDisplayOriginatingAddress());

  24. strb.append(" 信息内容 ");

  25. strb.append(msg.getDisplayMessageBody());

  26. }

  27. Toast.makeText(arg0, strb.toString(), Toast.LENGTH_LONG).show();

  28. }

  29. }

当接收到短信息后,onReceive 方法被调用。由于 Android 设备接收到的 SMS 短信息是 PDU(Protocol Description Unit) 形式的,因此通过 Bundle 类对象获取到 PDUS,并创建 SmsMessage 对象。然后从 SmsMessage 对象中提取出短信息的相关信息,并存储到 StringBuilder 类的对象中,最后使用 Toast 显示出来。

测试该实例时,可通过 AVD Mananger,再启动一个 AVD,通过 AVD 的短信程序向当前 AVD 号码发送短信,就可使该实例被触发运行。

发送短信

要实现发送短信功能,需要在 AndroidManifest.xml 文件中注册发送短信的权限,然后才可以使用发送短信功能。代码如下:

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

发送短信使用的是 android.telephony.SmsManager 类的 sendTextMessage 方法,该方法定义如下:

public void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)

其中,各个参数的意义如下。

  • destinationAddress:表示接收短信的手机号码。

  • scAddress:短信服务中心号码,设置为 null 表示使用手机默认的短信服务中心。

  • text:要发送的短信内容。

  • sentIntent:当消息被成功发送给接收者时,广播该 PendingIntent。

  • deliveryIntent:当消息被成功发送时,广播该 PendingIntent。

短信发送实例

实例sendMessageDemo 演示了发送短信的过程,其运行效果如图 1 所示。

sendMessageDemo实例

图 1  sendMessageDemo实例

在实例 sendMessageDemo 中,main.xml 的代码如下:


  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="fill_parent"

  4. android:layout_height="fill_parent"

  5. android:orientation="vertical">


  6. <LinearLayout

  7. android:layout_width="fill_parent"

  8. android:layout_height="wrap_content"

  9. android:orientation="horizontal">


  10. <TextView

  11. android:id="@+id/textview01"

  12. android:layout_width="wrap_content"

  13. android:layout_height="wrap_content"

  14. android:layout_marginLeft="15dp"

  15. android:text="收件人" />


  16. <EditText

  17. android:id="@+id/edittext01"

  18. android:layout_width="fill_parent"

  19. android:layout_height="wrap_content"

  20. android:layout_marginLeft="20dp" />


  21. </LinearLayout>


  22. <LinearLayout

  23. android:layout_width="fill_parent"

  24. android:layout_height="wrap_content"

  25. android:layout_marginTop="30dp"

  26. android:orientation="horizontal">


  27. <TextView

  28. android:id="@+id/textview02"

  29. android:layout_width="wrap_content"

  30. android:layout_height="wrap_content"

  31. android:layout_marginLeft="15dp"

  32. android:text="@string/receiver" />


  33. <EditText

  34. android:id="@+id/edittext02"

  35. android:layout_width="fill_parent"

  36. android:layout_height="wrap_content"

  37. android:layout_marginLeft="10dp" />

  38. </LinearLayout>


  39. <Button

  40. android:id="@+id/button"

  41. android:layout_width="wrap_content"

  42. android:layout_height="wrap_content"

  43. android:layout_marginLeft="100dp"

  44. android:layout_marginTop="30dp"

  45. android:text="@string/msg" />

  46. </LinearLayout>

在实例 sendMessageDemo 中,AndroidManifest.xml 的代码如下:


  1. <?xml version="1.0" encoding="utf-8"?>

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  3. package="introduction.android.receivemessagedemo"

  4. android:versionCode="1"

  5. android:versionName="1.0">


  6. <uses-sdk android:minSdkVersion="14" />

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

  8. <application

  9. android:allowBackup="true"

  10. android:icon="@mipmap/ic_launcher"

  11. android:label="@string/app_name"

  12. android:roundIcon="@mipmap/ic_launcher_round"

  13. android:supportsRtl="true"

  14. android:theme="@style/AppTheme">

  15. <activity android:name=".MainActivity">

  16. <intent-filter>

  17. <action android:name="android.intent.action.MAIN" />

  18. <category android:name="android.intent.category.LAUNCHER" />

  19. </intent-filter>

  20. </activity>

  21. <receiver android:name="SmsReceiver">

  22. <intent-filter>

  23. <action android:name="android.provider.Telephony.SMS_RECEIVED" />

  24. </intent-filter>

  25. </receiver>

  26. </application>


  27. </manifest>

在实例 sendMessageDemo 中,MainActivity.java 实现了发送短信的功能,其代码如下:


  1. package introduction.android.receivemessagedemo;


  2. import android.app.Activity;

  3. import android.os.Bundle;

  4. import android.telephony.SmsManager;

  5. import android.view.View;


  6. import android.view.View.OnClickListener;

  7. import android.widget.Button;

  8. import android.widget.EditText;

  9. import android.widget.Toast;


  10. public class MainActivity extends Activity {

  11. /**

  12.     * Called when the activity is first created.

  13.     */

  14. private Button button;

  15. private EditText edittext01, edittext02;


  16. @Override

  17. public void onCreate(Bundle savedInstanceState) {

  18. super.onCreate(savedInstanceState);

  19. setContentView(R.layout.activity_main);

  20. button = (Button) findViewById(R.id.button);

  21. button.setOnClickListener(new buttonListener());

  22. }


  23. class buttonListener implements OnClickListener {

  24. @Override

  25. public void onClick(View v) {

  26. // TODO Auto-generated method stub

  27. edittext01 = (EditText) findViewById(R.id.edittext01);

  28. edittext02 = (EditText) findViewById(R.id.edittext02);

  29. String number = edittext01.getText().toString();

  30. //获取手机号码

  31. String messageOl = edittext02.getText().toString();

  32. //获取短信内容

  33. if (number.equals("") || messageOl.equals(""))

  34. //判断输入是否有空格

  35. {

  36. Toast.makeText(MainActivity.this, "输入有误,请检查输入",

  37. Toast.LENGTH_LONG).show();

  38. } else {

  39. SmsManager massage = SmsManager.getDefault();

  40. massage.sendTextMessage(number, null, messageOl, null, null);

  41. //调用senfTextMassage方法来发送短信

  42. Toast.makeText(MainActivity.this, "短信发送成功",

  43. Toast.LENGTH_LONG).show();

  44. }

  45. }

  46. }

  47. }

在实际应用该短信发送程序时,要注意一些限制问题,比如接收手机号码的格式、短信内容超过预定字符的提示等。

一般情况下,手机号码格式可以使用 Pattern 来设置,此外 Android SDK 提供了 PhoneNumberUtils 类来对电话号码格式进行处理,而短信内容超过 70 个字符会被自动分解为多条短信发送,在此不做具体描述。

特别声明:
1、如无特殊说明,内容均为本站原创发布,转载请注明出处;
2、部分转载文章已注明出处,转载目的为学习和交流,如有侵犯,请联系客服删除;
3、编辑非《源码码网》的文章均由用户编辑发布,不代表本站立场,如涉及侵犯,请联系删除;
全部评论(0)
推荐阅读
  • 基于NetCore(Razor Page)开发的Cms建站系统MIT协议
  • 基于NetCore(Razor Page)开发的Cms建站系统MIT协议
  • FytSoaCms一款基于NetCore2.2/3.1(RazorPage)功能强大的Cms建站系统,支持前后端分离。简介:模块化:全新的架构和模块化的开发机制,便于灵活扩展和二次开发。模型/栏目/分类信息体系:通过栏目和模型绑定,以及不同的模型类型,不同栏目可以实现差异化的功能,轻松实现诸如资讯、下载、讨论和图片等功能。通过分类信息和栏目绑定,可以自动建立索引表,轻松实现复杂的信息检索。FytSoa是一套基于NetCore+SqlS
  • 开发工具
  • 来源:gitee
  • 编辑:源码码网
  • 时间:2026-01-24 22:21
  • 阅读:255
  • 基于JAVA开发的企业级平台微信公众号管理系统SmartWx
  • 基于JAVA开发的企业级平台微信公众号管理系统SmartWx
  • SmartWx微信公众号管理系统是一个完整的微信公众号web操作版,直接编译即可运行。让用户不再用关心微信的底层接口,直接使用页面进行操作,简单方便。包括服务器绑定、文本管理、图文管理、菜单管理、粉丝管理、群发消息等。技术框架开发语言:JAVA数据库:MYSQLJAVA开发框架:SpringMVC+Spring+Mybatis缓存框架:j2cache前端开发框架:Layui+JQuery+html前台模板引擎:art-templat
  • 源码教程
  • 来源:gitee
  • 编辑:源码码网
  • 时间:2026-01-24 21:53
  • 阅读:255
  • 前后端分离的Java快速开发平台renren-security可免费商用
  • 前后端分离的Java快速开发平台renren-security可免费商用
  • renren-security是一个轻量级的,前后端分离的Java快速开发平台,能快速开发项目并交付【接私活利器】采用SpringBoot3.x、Shiro、MyBatis-Plus、Vue3、TypeScript、ElementPlus、VueRouter、Pinia、Axios、Vite框架,开发的一套权限系统,极低门槛,拿来即用。设计之初,就非常注重安全性,为企业系统保驾护航,让一切都变得如此简单。提供了代码生成器,只
  • 源码教程
  • 来源:gitee
  • 编辑:源码码网
  • 时间:2026-01-23 13:03
  • 阅读:157
  • 离线IP地址定位库和IP定位数据管理框架Ip2region
  • 离线IP地址定位库和IP定位数据管理框架Ip2region
  • Ip2region是什么ip2region -是一个离线IP地址定位库和IP定位数据管理框架,同时支持IPv4和IPv6,10微秒级别的查询效率,提供了众多主流编程语言的 xdb 数据生成和查询客户端实现。Ip2region特性1、离线定位库项目本身同时了提供了一份IPv4(data/ipv4_source.txt)和IPv6(data/ipv6_source.txt)的原始数据和对应的xd
  • 源码教程
  • 来源:gitee
  • 编辑:源码码网
  • 时间:2026-01-22 11:26
  • 阅读:208
  • 常用测试压力工具使用介绍
  • 常用测试压力工具使用介绍
  • ab 是 ApacheBench 工具的缩写,它是一个HTTP压力测试工具。让我详细说明如何测试:1. 安装ApacheBenchWindows系统:方法一:安装XAMPP或WAMP(自带ab)下载地址:https://www.apachefriends.org/zh_cn/index.html安装后,ab工具在:C:xamppapacheinab.exe方法二:使
  • 开发工具
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2026-01-13 20:27
  • 阅读:143
联系客服
源码代售 源码咨询 技术开发 联系客服
029-84538663
手机版

扫一扫进手机版
返回顶部