源码教程 2025年06月7日
0 收藏 0 点赞 627 浏览 7834 个字
摘要 :

在学接收短信和发送短信之前,先简单介绍一下 SMS 短消息服务。SMS(Short Message Service,短信息服务)是一种存储和转发服务。也就是说,短信息并不是直接从发信人发……

在学接收短信发送短信之前,先简单介绍一下 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 所示。

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

图 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 所示。

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

图 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 个字符会被自动分解为多条短信发送,在此不做具体描述。

微信扫一扫

支付宝扫一扫

版权: 转载请注明出处:https://www.zuozi.net/973.html

管理员

相关推荐
2025-07-05

对于一些使用WordPress进行外贸建站的商家来说,大部分人会通过在WordPress中添加JS代码和CSS样式表…

708
2025-07-05

当商家遇到WordPress独立站改版或者域名到期等问题时,不免会涉及到WordPress域名的更改,那么这一…

726
2025-07-05

用户在使用WooCommerce进行跨境电商独立站搭建工作时,有可能会借助WooCommerce短代码实现更加醒目…

315
2025-07-05

随着外贸建站行业的不断深入发展,WordPress的多语言功能也显得越来越重要,一个具有多语言的独立站…

1,050
2025-07-05

WooCommerce作为WordPress外贸建站生态的一部分,WooCommerce运费设置是商家在建站过程中不可忽视的…

843
2025-07-05

在外贸建站的过程中,有些商家会选择使用WordPress幻灯片为网站页面增加一定的动感和可观性,进而提…

729
发表评论
暂无评论

还没有评论呢,快来抢沙发~

助力内容变现

将您的收入提升到一个新的水平

点击联系客服

在线时间:08:00-23:00

客服QQ

122325244

客服电话

400-888-8888

客服邮箱

122325244@qq.com

扫描二维码

关注微信客服号