您好!欢迎来到源码码网

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

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

在学接收短信和发送短信之前,先简单介绍一下 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)
推荐阅读
  • bootstrap ui框架能用在uniapp中吗?
  • bootstrap ui框架能用在uniapp中吗?
  • BootstrapUI框架通常是前端开发中的一种工具,它提供了一套预定义的CSS样式和组件,用于快速构建响应式布局的网页。然而,UniApp是一个使用Vue.js开发跨平台应用的框架,它可以用来开发iOS、Android、以及各种小程序和H5应用。
  • 互动社区
  • 来源:源码码网
  • 编辑:热度建站
  • 时间:2024-04-12 00:04
  • 阅读:184
  • css实现banner图由中心点动态放大效果
  • css实现banner图由中心点动态放大效果
  • 在日常的网页设计中,为了让网页增加一定的特效以达到交互的目的,我们尝尝会在网页中使用一些动画效果。今天来说说实现banner图由中心点动态放大效果,实现这个效果需要用到css中的动画:animation​和关键帧:@keyframes,具体示例如下:
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-04-11 18:52
  • 阅读:197
  • countUp.js实现鼠标滑动到某个位置数字自动滚动增加的效果
  • countUp.js实现鼠标滑动到某个位置数字自动滚动增加的效果
  • 在网页开发中为了提升网页的交互效果,经常会用到使用js给网页增加一定的特效,下边就来说说使用js实现鼠标滑动到某个位置数字自动滚动增加的效果。其实这种效果有很多中解决办法,自己也可以去写,下边我们借助countUp.js来实现,关于这个js文件,我放在末尾:
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-04-08 09:20
  • 阅读:273
  • 响应式网页设计思路及注意事项
  • 响应式网页设计思路及注意事项
  • 一、什么是响应式网页响应式网页设计就是让网页具有根据设备类型应用CSS样式的能力。设计:设想、计划。设计就是把想法实现。网页设计:按照一定的设计思路布局网页内容。传统网页设计:都是针对PC端浏览器而设计的,不具备查询设备的能力,更不能对多种访问设备做出响应。传统网页设计的弊端:在移动互联网时代,传统的网页设计不适合多屏幕时代。响应式网页设计应运而生。响应式网页设计是一种设计网页的思想/方法。响应:指让我们的网页能够自动查询用户的访问设备
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-04-02 11:24
  • 阅读:180
  • css中rel的属性值都有哪些,分别代表什么意思
  • css中rel的属性值都有哪些,分别代表什么意思
  • 在HTML中,元素的rel属性用于定义当前文档与被链接文档之间的关系。这个属性在CSS的上下文中经常与样式表关联,但rel属性的用途远不止于此。以下是一些常见的rel属性值及其意义:1、stylesheet:表示被链接的文档是一个样式表。这通常用于链接CSS文件。
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-03-28 12:28
  • 阅读:309
联系客服
源码代售 源码咨询 素材咨询 联系客服
029-84538663
手机版

扫一扫进手机版
返回顶部