【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 1509|回复: 1

Android 开发之旅:短信的收发及在android模拟器之间实践

[复制链接]
发表于 2013-1-26 00:45:07 | 显示全部楼层 |阅读模式
引言本文通过运行两个Android模拟器,介绍在Android中如何实现短信服务(SMS,short message service)的功能。通过这个例子,我想带给大家的是:更加熟悉之前介绍过的Android应用程序的概念及技术细节,且通过实例调度大家的兴趣。我之所以选择SMS为例子,主要原因是SMS已经非常成熟了,从中可以发掘更多的信息和技术细节,而且我相信大部分人发短信比打电话多。
本文的主要内容如下:
  • 1、温故知新
  • 2、准备工作:SMS涉及的主要类SmsManager
  • 3、简单的SMS发送程序
    • 3.1、运行SMS程序给另一个android模拟器发短
  • 4、SMS增强(一)
  • 5、SMS增强(二)
  • 6、SMS接收程序(下篇)
  • 7、emulator工具(下篇)
  • 8、…
1、温故知新 广播接收者:一个广播接收者是这样一个组件,它不做什么事,仅是接受广播公告并作出相应的反应。许多广播源自于系统代码,例如公告时区的改变、电池电量低、已采取图片、用户改变了语言偏好。应用程序也可以发起广播,例如为了他其他程序知道某些数据已经下载到设备且他们可以使用这些数据
BroadcastReceiver类:是接受sendBroadcast()发送的意图(intents)的基类。可以用Context.registerReceiver()动态地注册这个类的实例,或者通过AndroidManifest.xml中<receiver>标签静态发布。
广播接收者不显示一个用户界面。然而,它们启动一个活动去响应收到的信息,或者他们可能使用NotificationManager去通知用户。通知可以使用多种方式获得用户的注意——闪烁的背光、振动设备、播放声音等等。典型的是放在一个持久的图标在状态栏,用户可以打开获取信息。
2、准备工作:SMS涉及的主要类SmsManager实现SMS主要用到SmsManager类,该类继承自java.lang.Object类,下面我们介绍一下该类的主要成员。
公有方法:
  • ArrayList<String> divideMessage(String text)
    当短信超过SMS消息的最大长度时,将短信分割为几块。
    参数text——初始的消息,不能为空
    返回值:有序的ArrayList<String>,可以重新组合为初始的消息
  • static SmsManager getDefault()
    获取SmsManager的默认实例。
    返回值SmsManager的默认实例
  • void SendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)
    发送一个基于SMS的数据到指定的应用程序端口。
    参数
    1)、destinationAddress——消息的目标地址
    2)、scAddress——服务中心的地址or为空使用当前默认的SMSC 3)destinationPort——消息的目标端口号
    4)、data——消息的主体,即消息要发送的数据
    5)、sentIntent——如果不为空,当消息成功发送或失败这个PendingIntent就广播。结果代码是Activity.RESULT_OK表示成功,或RESULT_ERROR_GENERIC_FAILURE、RESULT_ERROR_RADIO_OFF、RESULT_ERROR_NULL_PDU之一表示错误。对应RESULT_ERROR_GENERIC_FAILURE,sentIntent可能包括额外的“错误代码”包含一个无线电广播技术特定的值,通常只在修复故障时有用。
    每一个基于SMS的应用程序控制检测sentIntent。如果sentIntent是空,调用者将检测所有未知的应用程序,这将导致在检测的时候发送较小数量的SMS。
    6)、deliveryIntent——如果不为空,当消息成功传送到接收者这个PendingIntent就广播。
    异常:如果destinationAddressdata是空时,抛出IllegalArgumentException异常。
  • void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String>parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliverIntents)
    发送一个基于SMS的多部分文本,调用者应用已经通过调用divideMessage(String text)将消息分割成正确的大小。
    参数
    1)、destinationAddress——消息的目标地址
    2)、scAddress——服务中心的地址or为空使用当前默认的SMSC
    3)、parts——有序的ArrayList<String>,可以重新组合为初始的消息
    4)、sentIntents——跟SendDataMessage方法中一样,只不过这里的是一组PendingIntent
    5)、deliverIntents——跟SendDataMessage方法中一样,只不过这里的是一组PendingIntent
    异常:如果destinationAddressdata是空时,抛出IllegalArgumentException异常。
  • void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
    发送一个基于SMS的文本。参数的意义和异常前面的已存在的一样,不再累述。
常量:
  • public static final int RESULT_ERROR_GENERIC_FAILURE
    表示普通错误,值为1(0x00000001)
  • public static final int RESULT_ERROR_NO_SERVICE
    表示服务当前不可用,值为4 (0x00000004)
  • public static final int RESULT_ERROR_NULL_PDU
    表示没有提供pdu,值为3 (0x00000003)
  • public static final int RESULT_ERROR_RADIO_OFF
    表示无线广播被明确地关闭,值为2 (0x00000002)
  • public static final int STATUS_ON_ICC_FREE
    表示自由空间,值为0 (0x00000000)
  • public static final int STATUS_ON_ICC_READ
    表示接收且已读,值为1 (0x00000001)
  • public static final int STATUS_ON_ICC_SENT
    表示存储且已发送,值为5 (0x00000005)
  • public static final int STATUS_ON_ICC_UNREAD
    表示接收但未读,值为3 (0x00000003)
  • public static final int STATUS_ON_ICC_UNSENT
    表示存储但为发送,值为7 (0x00000007)
  • 3、简单的SMS发送程序1)、首先,编辑布局文件res/layout/main.xml,达到我们想要的结果,界面如下:

    图1、程序运行界面

    对应的xml代码如下:
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3.     android:orientation="vertical"
    4.         android:layout_width="fill_parent"
    5.     android:layout_height="fill_parent" >
    6.     <TextView android:layout_width="fill_parent"
    7.                         android:layout_height="wrap_content"
    8.                         android:text="@string/txtPhoneNo"/>     <!-- text's value define in res/values/strings.xml -->
    9.    
    10.     <EditText android:layout_width="fill_parent"
    11.                         android:layout_height="wrap_content"
    12.                         android:id="@+id/edtPhoneNo"/>
    13.        
    14.     <TextView android:layout_width="fill_parent"
    15.                         android:layout_height="wrap_content"
    16.                         android:text="@string/txtContent"/>
    17.    
    18.     <EditText android:layout_width="fill_parent"
    19.                         android:layout_height="wrap_content"
    20.                         android:minLines="3"
    21.                         android:id="@+id/edtContent"/>
    22.    
    23.     <Button android:layout_width="wrap_content"
    24.                         android:layout_height="wrap_content"
    25.                         android:text="@string/btnText"
    26.                         android:id="@+id/btnSend"/>
    27. </LinearLayout>
    复制代码
    相应的要在res/values/strings.xm中添加上面定义的视图的text的值,如下:
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <resources>
    3.     <string name="txtPhoneNo">Please input phone NO:</string>
    4.     <string name="txtContent">Please input SMS\'s content:</string>
    5.     <string name="btnText">send!</string>
    6.     <string name="app_name">SMS</string>
    7. </resources>
    复制代码
    2)、做完这些准备工作之后,我么要开始编写代码实现简单的短信发送了。
    通过第一步我们构建好界面之后,现在要在上面的基础上编写业务逻辑了。大致过程为:在java源文件中,获取用户在edtPhoneNo中输入的电话号码,edtContent中输入要发送的内容;然后点击btnSend按钮发送短信,要达到这个目的我们要设置btnSend的OnClickListener以达到当点击它触发发送短信的功能,而且要发送短信就要用到我们前面介绍的SmsManager类提供的方法接口。
    设置btnSend的OnClickListener的代码如下:
    1. btnSend.setOnClickListener(new View.OnClickListener() {
    2.         public void onClick(View v) {
    3.                 String phoneNo = edtPhoneNo.getText().toString();
    4.                 String message = edtContent.getText().toString();
    5.                 if (phoneNo.length() > 0 && message.length() > 0){
    6.                         //call sendSMS to send message to phoneNo
    7.                         sendSMS(phoneNo, message);
    8.                 }
    9.                 else
    10.                         Toast.makeText(getBaseContext(),
    11.                                 "Please enter both phone number and message.",
    12.                                 Toast.LENGTH_SHORT).show();
    13.         }
    14. });
    复制代码
    发送短信的功能的代码如下:
    1. private void sendSMS(String phoneNumber, String message) {
    2.         // ---sends an SMS message to another device---
    3.         SmsManager sms = SmsManager.getDefault();
    4.         PendingIntent pi = PendingIntent.getActivity(this, 0,                 new Intent(this,TextMessage.class), 0);
    5.         //if message's length more than 70 ,
    6.         //then call divideMessage to dive message into several part          //and call sendTextMessage()
    7.         //else direct call sendTextMessage()
    8.         if (message.length() > 70) {
    9.                 ArrayList<String> msgs = sms.divideMessage(message);
    10.                 for (String msg : msgs) {
    11.                         sms.sendTextMessage(phoneNumber, null, msg, pi, null);
    12.                 }
    13.         } else {
    14.                 sms.sendTextMessage(phoneNumber, null, message, pi, null);
    15.         }
    16.         Toast.makeText(TextMessage.this, "短信发送完成", Toast.LENGTH_LONG).show();
    17. }
    复制代码
    如果你已经看了第2节介绍的SmsManager类的介绍,代码应该很好理解。在这里要说明的是,sendTextMessage方法中的第4个和第5个参数PendingIntent设为null,这样的话不能根据短信发出之后的状态做相应的事情,如短信发送失败后的提醒、接收者成功接收后的回执……完整的流程源码如下:
    1. package skynet.com.cnblogs.www;

    2. import java.util.ArrayList;

    3. import android.app.Activity;
    4. import android.app.PendingIntent;
    5. import android.content.Intent;
    6. import android.os.Bundle;
    7. import android.telephony.SmsManager;
    8. import android.view.View;
    9. import android.widget.*;

    10. public class TextMessage extends Activity {
    11.         /** Called when the activity is first created. */
    12.         @Override
    13.         public void onCreate(Bundle savedInstanceState) {
    14.                 super.onCreate(savedInstanceState);

    15.                 setContentView(R.layout.main);
    16.                 btnSend = (Button) findViewById(R.id.btnSend);
    17.                 edtPhoneNo = (EditText) findViewById(R.id.edtPhoneNo);
    18.                 edtContent = (EditText) findViewById(R.id.edtContent);

    19.                 btnSend.setOnClickListener(new View.OnClickListener() {
    20.                         public void onClick(View v) {
    21.                                 String phoneNo = edtPhoneNo.getText().toString();
    22.                                 String message = edtContent.getText().toString();
    23.                                 if (phoneNo.length() > 0 && message.length() > 0) {
    24.                                         // call sendSMS to send message to phoneNo
    25.                                         sendSMS(phoneNo, message);
    26.                                 } else
    27.                                         Toast.makeText(getBaseContext(),
    28.                                                         "Please enter both phone number and message.",
    29.                                                         Toast.LENGTH_SHORT).show();
    30.                         }
    31.                 });
    32.         }

    33.         private Button btnSend;
    34.         private EditText edtPhoneNo;
    35.         private EditText edtContent;

    36.         private void sendSMS(String phoneNumber, String message) {
    37.                 // ---sends an SMS message to another device---
    38.                 SmsManager sms = SmsManager.getDefault();
    39.                 PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
    40.                                 TextMessage.class), 0);
    41.                 // if message's length more than 70 ,
    42.                 // then call divideMessage to dive message into several part ,and call
    43.                 // sendTextMessage()
    44.                 // else direct call sendTextMessage()
    45.                 if (message.length() > 70) {
    46.                         ArrayList<String> msgs = sms.divideMessage(message);
    47.                         for (String msg : msgs) {
    48.                                 sms.sendTextMessage(phoneNumber, null, msg, pi, null);
    49.                         }
    50.                 } else {
    51.                         sms.sendTextMessage(phoneNumber, null, message, pi, null);
    52.                 }
    53.                 Toast.makeText(TextMessage.this, "短信发送完成", Toast.LENGTH_LONG).show();
    54.         }
    55. }
    复制代码
    3)运行前,还要在清单文件AndroidManifest.xml中加入允许发送短信的权限:
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3.       package="skynet.com.cnblogs.www"
    4.       android:versionCode="1"
    5.       android:versionName="1.0">
    6.     <application android:icon="@drawable/icon" android:label="@string/app_name">
    7.         <activity android:name=".TextMessage"
    8.                   android:label="@string/app_name">
    9.             <intent-filter>
    10.                 <action android:name="android.intent.action.MAIN" />
    11.                 <category android:name="android.intent.category.LAUNCHER" />
    12.             </intent-filter>
    13.         </activity>

    14.     </application>
    15.         <uses-permission android:name="android.permission.SEND_SMS"/>
    16. </manifest>
    复制代码
    3.1、运行SMS程序给另一个android模拟器发短信运行上面我们编写的TextMessage程序,另外在Windows的命令行下切换到tools目录下,并输入emulator –data smsReceiver,我的如下:

    这样就会启动一个android模拟器,如下所示:(注意它的编号:5556,就是用这个编号与它通信的

    图2、通过emulator启动一个android模拟器
    通过我们TextMessage程序启动的android模拟器,编写短信:
    图3、TextMessage程序个5556模拟器发短信
    点击发送之后,通过命令行启动的5556号android模拟器会收到我们刚才发送的短信,如下所示:

    图4、收到短信的提示
    tips:
    如果通过命令行的emulator启动android模拟器提示“NO DNS servers found!”,这时我们发的短信模拟器是收不到的。

    • 在Windows下,如果电脑没有介入网络,即找不DNS服务器的话会出现这种情况!
    • 在Mac下,如果提示这个警告的话,可以这样解决:检查你是否有/etc/resolv.conf文件,如果没有的话,通过下面的命令行
      ln -s /private/var/run/resolv.conf /etc/resolv.conf可以解决。
    4、SMS增强(一)上面我们实现了一个简单的SMS程序,下面我们要对它进行增强!你肯定已经注意到了,我们上面的SMS程序的sendTextMessage方法中的第4个和第5个参数PendingIntent设为null,即sentIntent和deliveryIntent。
    第4个参数-sendIntent,当消息成功发送或发送失败都将被触发。广播接收者的结果码,Activity.RESULT_OK表示成功,或RESULT_ERROR_GENERIC_FAILURE、RESULT_ERROR_RADIO_OFF、RESULT_ERROR_NULL_PDU之一表示错误。对应RESULT_ERROR_GENERIC_FAILURE,sentIntent可能包括额外的“错误代码”包含一个无线电广播技术特定的值,通常只在修复故障时有用。第5个参数-deliveryIntent,仅当目标接收到你的SMS消息才触发。
    为了跟踪发出的短信的状态,实现和注册Broadcast Receiver(广播接收者)监听传递给sendTextMessage方法的参数Pending Intents。下面我们就实现和注册这个广播接收者:
    1. String SENT_SMS_ACTION="SENT_SMS_ACTION";
    2. String DELIVERED_SMS_ACTION="DELIVERED_SMS_ACTION";

    3. //create the sentIntent parameter
    4. Intent sentIntent=new Intent(SENT_SMS_ACTION);
    5. PendingIntent sentPI=PendingIntent.getBroadcast(
    6.                 this,
    7.                 0,
    8.                 sentIntent,
    9.                 0);

    10. //create the deilverIntent parameter
    11. Intent deliverIntent=new Intent(DELIVERED_SMS_ACTION);
    12. PendingIntent deliverPI=PendingIntent.getBroadcast(
    13.                 this,
    14.                 0,
    15.                 deliverIntent,
    16.                 0);

    17. //register the Broadcast Receivers
    18. registerReceiver(new BroadcastReceiver(){
    19.         @Override
    20.         public void onReceive(Context _context,Intent _intent)
    21.         {
    22.                 switch(getResultCode()){
    23.                         case Activity.RESULT_OK:
    24.                                 Toast.makeText(getBaseContext(),
    25.                                                 "SMS sent success actions",
    26.                         Toast.LENGTH_SHORT).show();
    27.                                 break;
    28.                         case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
    29.                                 Toast.makeText(getBaseContext(),
    30.                                                 "SMS generic failure actions",
    31.                         Toast.LENGTH_SHORT).show();
    32.                                 break;
    33.                         case SmsManager.RESULT_ERROR_RADIO_OFF:
    34.                                 Toast.makeText(getBaseContext(),
    35.                                                 "SMS radio off failure actions",
    36.                         Toast.LENGTH_SHORT).show();
    37.                                 break;
    38.                         case SmsManager.RESULT_ERROR_NULL_PDU:
    39.                                 Toast.makeText(getBaseContext(),
    40.                                                 "SMS null PDU failure actions",
    41.                         Toast.LENGTH_SHORT).show();
    42.                                 break;
    43.                 }
    44.         }
    45. },
    46. new IntentFilter(SENT_SMS_ACTION));
    47. registerReceiver(new BroadcastReceiver(){
    48.         @Override
    49.         public void onReceive(Context _context,Intent _intent)
    50.         {
    51.                 Toast.makeText(getBaseContext(),
    52.                                 "SMS delivered actions",
    53.                 Toast.LENGTH_SHORT).show();                               
    54.         }
    55. },
    56. new IntentFilter(DELIVERED_SMS_ACTION));
    复制代码
    在基本完成了要做的工作,接下来要做的就是将sendTextMessage的第4个和第5个参数改为sentPI、deliverPI,这样工作基本完成,修改后的sendSMS方法如下:
    1. private void sendSMS(String phoneNumber, String message) {
    2.         // ---sends an SMS message to another device---
    3.         SmsManager sms = SmsManager.getDefault();
    4.         String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    5.         String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

    6.         // create the sentIntent parameter
    7.         Intent sentIntent = new Intent(SENT_SMS_ACTION);
    8.         PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,
    9.                         0);

    10.         // create the deilverIntent parameter
    11.         Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
    12.         PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0,
    13.                         deliverIntent, 0);

    14.         // register the Broadcast Receivers
    15.         registerReceiver(new BroadcastReceiver() {
    16.                 @Override
    17.                 public void onReceive(Context _context, Intent _intent) {
    18.                         switch (getResultCode()) {
    19.                         case Activity.RESULT_OK:
    20.                                 Toast.makeText(getBaseContext(),
    21.                                                 "SMS sent success actions", Toast.LENGTH_SHORT)
    22.                                                 .show();
    23.                                 break;
    24.                         case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
    25.                                 Toast.makeText(getBaseContext(),
    26.                                                 "SMS generic failure actions", Toast.LENGTH_SHORT)
    27.                                                 .show();
    28.                                 break;
    29.                         case SmsManager.RESULT_ERROR_RADIO_OFF:
    30.                                 Toast
    31.                                                 .makeText(getBaseContext(),
    32.                                                                 "SMS radio off failure actions",
    33.                                                                 Toast.LENGTH_SHORT).show();
    34.                                 break;
    35.                         case SmsManager.RESULT_ERROR_NULL_PDU:
    36.                                 Toast.makeText(getBaseContext(),
    37.                                                 "SMS null PDU failure actions", Toast.LENGTH_SHORT)
    38.                                                 .show();
    39.                                 break;
    40.                         }
    41.                 }
    42.         }, new IntentFilter(SENT_SMS_ACTION));
    43.         registerReceiver(new BroadcastReceiver() {
    44.                 @Override
    45.                 public void onReceive(Context _context, Intent _intent) {
    46.                         Toast.makeText(getBaseContext(), "SMS delivered actions",
    47.                                         Toast.LENGTH_SHORT).show();
    48.                 }
    49.         }, new IntentFilter(DELIVERED_SMS_ACTION));

    50.         // if message's length more than 70 ,
    51.         // then call divideMessage to dive message into several part ,and call
    52.         // sendTextMessage()
    53.         // else direct call sendTextMessage()
    54.         if (message.length() > 70) {
    55.                 ArrayList<String> msgs = sms.divideMessage(message);
    56.                 for (String msg : msgs) {
    57.                         sms.sendTextMessage(phoneNumber, null, msg, sentPI, deliverPI);
    58.                 }
    59.         } else {
    60.                 sms.sendTextMessage(phoneNumber, null, message, sentPI, deliverPI);
    61.         }
    62. }
    复制代码
    运行之后的,发送短信成功的话就可以看到如下界面:

    图5、增强SMS(一)
    5、SMS增强(二)下面这个增强是使SMS能够发送二进制数据。要发送数据要使用SmsManager类的sendDataMessage方法,跟sendTextMessage方法类似,只不过该方法多了一个目标端口的参数,构建该SMS的过程跟前面的类似这里就不在累述。
 楼主| 发表于 2013-1-26 00:47:09 | 显示全部楼层
前面我们介绍都只是如何发送SMS消息,接下来我们介绍如何接收SMS消息,及另一种发短信的方式并增强为可以发生图片等,最后介绍一下emulator工具。本文的主要内容如下:
6、温故知新之Intent此系列前面简单地接受过意图(Intent),这里再次简单介绍一下,在短信接收程序和使用Intent发送SMS中我们要用到。android应用程序的三大组件——Activities、Services、Broadcast Receiver,通过消息触发,这个消息就称作意图(Intent)。下面以Acitvity为例,介绍一下Intent。Android用Intent这个特殊的类实现在Activity与Activity之间的切换。Intent类用于描述应用的功能。在Intent的描述结构中,有两个最重要的部分:动作和动作对应的数据。典型的动作类型有MAIN、VIEW、PICK、EDIT等,我们在短信接收程序中就用到从广播意图中提取动作类型并判断是否是"android.provider.Telephony.SMS_RECEIVED",进而作深一步的处理。而动作对应的数据则以URI的形式表示。例如,要查看一个人的联系方式,需要创建一个动作为VIEW的Intent,以及表示这个人的URI。
通过解析各种Intent,从一个屏幕导航到另一个屏幕是很简单的。当向前导航时,Activity将会调用startActivity("指定一个Intent")方法。然后,系统会在所有已安装的应用程序中定义的IntentFilter中查找,找到最匹配的Intent对应的Activity。新的Activity接收到指定的Intent的通知后,开始运行。当startActivity()方法被调用时,将触发解析指定Intent的动作,该机制提供了两个关键的好处:
  • Activity能够重复利用从其他组件中以Intent形式产生的请求。
  • Activity可以在任何时候被具有相同IntentFilter的新的Activity取代。
7、准备工作:SmsMessage类顾名思义,SmsMessage类是一个表示短信的类,为了更好地了解Android的短信机制及以后更好地编写短信相关程序,这里介绍一下该类的公有方法和常量,及嵌套枚举、类成员。
公有方法:
  • public static int[]  calculateLength  (CharSequence  msgBody, boolean use7bitOnly)
    参数
    msgBody-要封装的消息、use7bitOnly-如果为TRUE,不是广播特定7-比特编码的部分字符被认为是单个空字符;如果为FALSE,且msgBody包含非7-比特可编码字符,长度计算使用16-比特编码。
    返回值
    返回一个4个元素的int数组,int[0]表示要求使用的SMS数量、int[1]表示编码单元已使用的数量、int[2]表示剩余到下个消息的编码单元数量、int[3]表示编码单元大小的指示器。
  • public static int[]  calculateLength  (String  messageBody, boolean use7bitOnly)
    参数返回值跟上面类似
  • public static SmsMessage   createFromPdu  (byte[] pdu)
    从原始的PDU(protocol description units)创建一个SmsMessage。这个方法很重要,在我们编写短信接收程序要用到,它从我们接收到的广播意图中获取的字节创建SmsMessage。
  • public String  getDisplayMessageBody()
    返回短信消息的主体,或者Email消息主体(如果这个消息来自一个Email网关)。如果消息主体不可用,返回null。这个方法也很重要,在我们编写短信接收程序也要用到。
  • public String   getDisplayOriginatingAddress  ()
    返回信息来源地址,或Email地址(如果消息来自Email网关)。如果消息主体不可用,返回null。这个方法在来电显示,短信接收程序中经常用到。
  • public String   getEmailBody  ()
    如果isEmail为TRUE,即是邮件,返回通过网关发送Email的地址,否则返回null。
  • public int  getIndexOnIcc  ()
    返回消息记录在ICC上的索引(从1开始的)
  • public String   getMessageBody  ()
    以一个String返回消息的主体,如果它存在且是基于文本的。
  • public SmsMessage.MessageClass   getMessageClass  ()
    返回消息的类。
  • public String   getOriginatingAddress  ()
    以String返回SMS信息的来电地址,或不可用时为null。
  • public byte[]  getPdu  ()
    返回消息的原始PDU数据。
  • public int  getProtocolIdentifier  ()
    获取协议标识符。
  • public String   getPseudoSubject  ()
  • public String   getServiceCenterAddress  ()
    返回转播消息SMS服务中心的地址,如果没有的话为null。
  • public int  getStatus  ()
    GSM:为一个SMS-STATUS-REPORT消息,它返回状态报告的status字段。这个字段表示之前提交的SMS消息的状态。
    CDMA:为不影响来自GSM的状态码,值移动到31-16比特。这个值由一个error类(25-16比特)和一个状态码(23-16比特)组成。
    如果是0,表示之前发送的消息已经被收到。
  • public int  getStatusOnIcc  ()
    返回消息在ICC上的状态(已读、未读、已发送、未发送)。有下面的几个值:SmsManager.STATUS_ON_ICC_FREE、SmsManager.STATUS_ON_ICC_READ、SmsManager.STATUS_ON_ICC_UNREAD、SmsManager.STATUS_ON_ICC_SEND、SmsManager.STATUS_ON_ICC_UNSENT这几个值在上篇的SmsManager类介绍有讲到。
  • public static SmsMessage.SubmitPdu   getSubmitPdu  (
           String  scAddress, String  destinationAddress,
           short destinationPort, byte[] data,
           boolean statusReportRequested)
    参数scAddress - 服务中心的地址(Sercvice Centre address,为null即使用默认的)、destinationAddress - 消息的目的地址、destinationPort- 发送消息到目的的端口号、data - 消息数据。
    返回值:一个包含编码了的SC地址(如果指定了的话)和消息内容的SubmitPdu,否则返回null,如果编码错误。
  • public static SmsMessage.SubmitPdu   getSubmitPdu  (
           String  scAddress, String  destinationAddress,
           String  message, boolean statusReportRequested)
    和上面类似。
  • public static int  getTPLayerLengthForPDU  (String  pdu)
    返回指定SMS-SUBMIT PDU的TP-Layer-Length,长度单位是字节而不是十六进字符。
  • public long  getTimestampMillis  ()
    以currentTimeMillis()格式返回服务中心时间戳。
  • public byte[]  getUserData  ()
    返回用户数据减去用户数据头部(如果有的话)
  • public boolean  isCphsMwiMessage  ()
    判断是否是CPHS MWI消息
  • public boolean  isEmail  ()
    判断是否是Email,如果消息来自一个Email网关且Email发送者(sender)、主题(subject)、解析主体(parsed body)可用,则返回TRUE。
  • public boolean  isMWIClearMessage  ()
    判断消息是否是一个CPHS 语音邮件或消息等待MWI清除(clear)消息。
  • public boolean  isMWISetMessage  ()
    判断消息是否是一个CPHS 语音邮件或消息等待MWI设置(set)消息。
  • public boolean  isMwiDontStore  ()
    如果消息是一个“Message Waiting Indication Group:Discard Message”通知且不应该保存,则返回TRUE,否则返回FALSE。
  • public boolean  isReplace  ()
    判断是否是一个“replace short message”SMS
  • public boolean  isReplyPathPresent  ()
    判断消息的TP-Reply-Path位是否在消息中设置了。
  • public boolean  isStatusReportMessage  ()
    判断是否是一个SMS-STATUS-REPORT消息。
常量值:
  • public static final int  ENCODING_16BIT :值为3(0x00000003)
  • public static final int  ENCODING_8BIT :值为2 (0x00000002)
  • public static final int  ENCODING_UNKNOWN :值为0 (0x00000000) ,用户数据编码单元的大小。
  • public static final int  MAX_USER_DATA_BYTES :值为140 (0x0000008c),表示每个消息的最大负载字节数。
  • public static final int  MAX_USER_DATA_BYTES_WITH_HEADER :134 (0x00000086),如果一个用户数据有头部,该值表示它的最大负载字节数,该值假定头部仅包含CONCATENATED_8_BIT_REFENENCE元素。
  • public static final int  MAX_USER_DATA_SEPTETS :值为160 (0x000000a0) ,表示每个消息的最大负载septets数。
  • public static final int  MAX_USER_DATA_SEPTETS_WITH_HEADER :值为153 (0x00000099),如果存在用户数据头部,则该值表示最大负载septets数该值假定头部仅包含CONCATENATED_8_BIT_REFENENCE元素。
嵌套枚举成员SmsMessage.MessageClass的枚举值:
  • public static final SmsMessage.MessageClass   CLASS_0
  • public static final SmsMessage.MessageClass   CLASS_1
  • public static final SmsMessage.MessageClass   CLASS_2
  • public static final SmsMessage.MessageClass   CLASS_3
  • public static final SmsMessage.MessageClass   CLASS_UNKNOWN
嵌套枚举成员SmsMessage.MessageClass的公有方法:
  • public static SmsMessage.MessageClass valueOf (String name):返回值的字符串的值
  • public static final MessageClass[]   values  ():返回MessageClass的值数组
嵌套类成员SmsMessage.SubmitPdu的字段:
  • public byte[]  encodedMessage :编码了的消息
  • public byte[]  encodedScAddress :编码的服务中心地址
嵌套类成员SmsMessage.SubmitPdu的公有方法:
  • public String   toString  ()
    返回一个包含简单的、可读的这个对象的描述字符串。鼓励子类去重写这个方法,并提供实现对象的类型和数据。默认实现简单地连接类名、@、十六进制表示的对象哈希码,即下面的形式: getClass().getName() + '@' + Integer.toHexString(hashCode())
8、SMS接收程序当一个SMS消息被接收时,一个新的广播意图由android.provider.Telepony.SMS_RECEIVED动作触发。注意:这个一个字符串字面量(string  literal),但是SDK当前并没有包括这个字符串的引用,因此当要在应用程序中使用它时必须自己显示的指定它。现在我们就开始构建一个SMS接收程序:
1)、跟SMS发送程序类似,要在清单文件AndroidManifest.xml中指定权限允许接收SMS:<uses-permission android:name="android.permission.RECEIVER_SMS"/>
为了能够回发短信,还应该加上发送的权限。
2)、应用程序监听SMS意图广播,SMS广播意图包含了到来的SMS细节。我们要从其中提取出SmsMessage对象,这样就要用到pdu键提取一个SMS PDUs数组(protocol description units—封装了一个SMS消息和它的元数据),每个元素表示一个SMS消息。为了将每个PDU byte数组转化为一个SMS消息对象,需要调用SmsMessage.createFromPdu
每个SmsMessage包含SMS消息的详细信息,包括起始地址(电话号码)、时间戳、消息体。下面编写一个接收短信的类SmsReceiver代码如下:
  1. package skynet.com.conblogs.www;

  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.telephony.SmsManager;
  7. import android.telephony.SmsMessage;
  8. import android.widget.Toast;

  9. public class SmsReceiver extends BroadcastReceiver {
  10.         @Override
  11.         public void onReceive(Context _context, Intent _intent) {
  12.                 if (_intent.getAction().equals(SMS_RECEIVER)) {
  13.                         SmsManager sms = SmsManager.getDefault();

  14.                         Bundle bundle = _intent.getExtras();
  15.                         if (bundle != null) {
  16.                                 Object[] pdus = (Object[]) bundle.get("pdus");
  17.                                 SmsMessage[] messages = new SmsMessage[pdus.length];
  18.                                 for (int i = 0; i < pdus.length; i++)
  19.                                         messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
  20.                                 for (SmsMessage message : messages) {
  21.                                         String msg = message.getMessageBody();
  22.                                         String to = message.getOriginatingAddress();
  23.                                         if (msg.toLowerCase().startsWith(queryString)) {
  24.                                                 String out = msg.substring(queryString.length());
  25.                                                 sms.sendTextMessage(to, null, out, null, null);

  26.                                                 Toast.makeText(_context, "success",
  27.                                                                 Toast.LENGTH_LONG).show();
  28.                                         }
  29.                                 }
  30.                         }
  31.                 }
  32.         }
  33.    
  34.         private static final String queryString="@echo";
  35.         private static final String SMS_RECEIVER=
  36.                 "android.provider.Telephony.SMS_RECEIVED";
  37. }
复制代码
上面代码的功能是从接收到的广播意图中提取来电号码、短信内容,然后将短信加上@echo头部回发给来电号码,并在屏幕上显示一个Toast消息提示成功。
9、另一种发送短信的方式:使用Intent上篇我们使用SmsManager类实现了发送SMS的功能,且并没有用到内置的客户端。实际上,我们很少这样做,自己在应用程序中去完全实现一个完整的SMS客户端。相反我们会去利用它,将需要发送的内容和目的手机号传递给内置的SMS客户端,然后发送。
下面我就向大家介绍如何利用Intent实现利用将我们的东西传递给内置SMS客户端发送我们SMS。为了实现这个功能,就要用到startActivity("指定一个Intent")方法,且指定Intent的动作为Intent.ACTION_SENDTO,用sms:指定目标手机号,用sms_body指定信息内容。java源文件如下所示:
  1. package skynet.com.cnblogs.www;

  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.net.Uri;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.Toast;


  10. public class TextMessage extends Activity {
  11.         /** Called when the activity is first created. */
  12.         @Override
  13.         public void onCreate(Bundle savedInstanceState) {
  14.                 super.onCreate(savedInstanceState);

  15.                 setContentView(R.layout.main);
  16.                 btnSend = (Button) findViewById(R.id.btnSend);
  17.                 edtPhoneNo = (EditText) findViewById(R.id.edtPhoneNo);
  18.                 edtContent = (EditText) findViewById(R.id.edtContent);

  19.                 btnSend.setOnClickListener(new View.OnClickListener() {
  20.                         public void onClick(View v) {
  21.                                 String phoneNo = edtPhoneNo.getText().toString();
  22.                                 String message = edtContent.getText().toString();
  23.                                 if (phoneNo.length() > 0 && message.length() > 0) {
  24.                                          Intent smsIntent=new Intent(Intent.ACTION_SENDTO,
  25.                                                          Uri.parse("sms:"+edtPhoneNo.getText().toString()));
  26.                                          smsIntent.putExtra("sms_body", edtContent.getText().toString());
  27.                                          TextMessage.this.startActivity(smsIntent);
  28.                                 } else
  29.                                         Toast.makeText(getBaseContext(),
  30.                                                         "Please enter both phone number and message.",
  31.                                                         Toast.LENGTH_SHORT).show();
  32.                         }
  33.                 });
  34.         }

  35.         private Button btnSend;
  36.         private EditText edtPhoneNo;
  37.         private EditText edtContent;
  38. }
复制代码
注意代码中的红色粗体部分,就是实现这个功能的核心代码!布局文件maim.xml和值文件string.xml跟上篇中的一样,这里不再累述。运行结果如下图:

图2、程序主界面
点击send按钮之后,转到内置的SMS客户端并且将我们输入的值传入了,如下图:

图3、内容传至内置SMS客户端
发送之后,5556号android模拟器会收到我们发送的消息,如下图:
图5、发送之后5556号android模拟器收到消息
10、增强SMS为MMS我们讲了这么多,都还只是实现了简单的发生SMS的功能,如果我们想发送图片、音频怎么办(⊙o⊙)?不急,现在我们就将第9节介绍的SMS发送程序改造为MMS。
我们可以附加一个文件到我们的消息做为附件发送,用Intent.EXTRA_STREAM和附件资源的Uri做为参数调用putExtra()方法,附加到信息。并设置Intent的类型为mime-type要注意的是:内置的MMS并不包括一个ACTION_SENDTO动作的Intent接收器,我们需要使用的动作类型是ACTION_SEND,并且目标手机号不在是使用sms:而是address主要代码如下:
  1. <strong><span style="color: rgb(0, 128, 0);">// Get the URI of a piece of media to attach.</span>
  2. Uri attached_Uri = Uri.parse("<span style="color: rgb(139, 0, 0);">content://media/external/images/media/1</span>");
  3. <span style="color: rgb(0, 128, 0);">// Create a new MMS intent</span>
  4. Intent mmsIntent = <span style="color: rgb(0, 0, 255);">new</span> Intent(Intent.ACTION_SEND, attached_Uri);
  5. mmsIntent.putExtra("<span style="color: rgb(139, 0, 0);">sms_body</span>", edtContent.getText().toString());
  6. mmsIntent.putExtra("<span style="color: rgb(139, 0, 0);">address</span>", edtPhoneNo.getText().toString());
  7. mmsIntent.putExtra(Intent.EXTRA_STREAM, attached_Uri);
  8. mmsIntent.setType("<span style="color: rgb(139, 0, 0);">image/png</span>");
  9. startActivity(mmsIntent);</strong>
复制代码
将这段代码替换第9节中的红色粗体代码,就完成而来一个MMS的构建。
PS:这篇文章本应该很早就该发出来了,在6月20号就写好了,但由于现在的工作环境完全隔离了Internet,家里又还没有开通网络;还有一个原因是现在工作比较忙!请大家见谅,能够继续支持我,让我有动力写下去。还有一点,这篇文章在我电脑上放久了,对当时的状态有些忘了,不知道文中有什么遗漏和错误,请大家指出!



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-6-26 11:01

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表