您好!欢迎来到源码码网

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

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

在学接收短信和发送短信之前,先简单介绍一下 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)
推荐阅读
  • 大型后台管理系统,用户登录状态该如何保存?
  • 大型后台管理系统,用户登录状态该如何保存?
  • 大型后台管理系统的用户登录状态保存需要综合考虑安全性、用户体验和系统架构。以下是企业级的完整方案:1.多层级存储策略class AuthManager {    constructor() {        this.storage = { &n
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-11-06 12:16
  • 阅读:350
  • 源码交易平台的支付困局与解决方案:如何通过专业支付系统提升交易效率
  • 源码交易平台的支付困局与解决方案:如何通过专业支付系统提升交易效率
  • 在数字经济蓬勃发展的今天,源码交易市场已成为互联网创业者和开发商的重要资源池。从电商系统源码到社交应用框架,从小程序解决方案到企业级管理系统,越来越多的开发者、初创企业和传统商家通过源码交易平台快速获取技术资产,实现商业目标的加速。源码交易市场的繁荣反映了数字化转型的迫切需求——企业需要快速迭代,开发者需要快速变现,用户需要快速启动。然而,在这个高速发展的市场中,一个长期被忽视但至关重要的问题浮现出来:支付系统的效率与安全性已成为制约交
  • 行业资讯
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-10-23 15:16
  • 阅读:297
  • Spring Boot 工程中 maven-surefire-plugin 测试执行失败及解决方法
  • Spring Boot 工程中 maven-surefire-plugin 测试执行失败及解决方法
  • 在SpringBoot工程编译时遇到maven-surefire-plugin的测试执行失败错误(Failedtoexecutegoalorg.apache.maven.plugins:maven-surefire-plugin:3.5.3:test),通常与测试环节相关。以下是常见原因及解决方法:1.测试用例执行失败• 原因:最常见的是测试用例(*Test.java)运行时抛出异常(如断言失败、空指针等),导
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-10-13 10:57
  • 阅读:362
  • WeMark - 微信小程序图片水印
  • WeMark - 微信小程序图片水印
  • 一个纯前端的微信小程序图片水印工具。支持文字/图片水印、单个与全屏两种模式,透明度与角度调节、单个水印位置X/Y控制,预览与对比模态、历史记录(100条)等功能。
  • 源码教程
  • 来源:源码码用户
  • 编辑:yg
  • 时间:2025-09-22 16:09
  • 阅读:287
联系客服
源码代售 源码咨询 素材咨询 联系客服
029-84538663
手机版

扫一扫进手机版
返回顶部