17 Star 24 Fork 336

OpenHarmony / telephony_sms_mms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

短彩信

简介

短彩信模块为移动数据用户提供短信收发和彩信编解码功能,主要功能有GSM/CDMA短信收发、短信PDU(Protocol data unit,协议数据单元)编解码、Wap Push接收处理 、小区广播接收、彩信通知、 彩信编解码和SIM卡短信记录增删改查等。

图 1 短彩信模块架构图

短彩信模块由接口管理类、短信发送管理类、短信接收管理类,和彩信编解码工具类组成。其中:

  • 接口管理类:SmsInterfaceManager 负责对外提供短信发送、SIM卡短信记录操作和配置相关接口,负责创建SmsSendManager 、SmsReceiveManager和smsMiscManager 对象。
  • 短信发送管理类: SmsSendManager创建GSM(GsmSmsSender) 、CDMA(CdmaSmsSender) 和网络策略管理(SmsNetworkPolicyManager)对象,并根据网络制式调度对应的GSM或CDMA对象发送短信。
  • 短信接收管理类: SmsReceiveManager 负责短信接收,监听来自RIL层的新短信信息;创建GSM(GsmSmsReceiveHandler) 和CDMA(CdmaSmsReceiveHandler) 对象;创建SmsWapPushHandler 和SmsCellBroadcastHandler 对象。
  • 彩信编解码类:负责彩信PDU的编解码处理。
  • Misc管理类:负责Sim卡短信操作、小区广播配置、短信服务中心地址配置和默认卡槽配置等。
  • IMS短信管理类:ImsSmsClient 负责IMS短信发送,及设置/获取IMS短信配置信息。

目录

/base/telephony/sms_mms
├─ common                       # 内部公共代码
├─ figures                      # Readme资源文件
├─ frameworks                   # 短彩信内部框架接口层
│  ├─ js                        # js相关代码
│  └─ native                    # native相关代码
├─ interfaces                   # 接口目录
│  ├─ innerkits                 # 部件间的内部接口
│  │ └─  ims                    # IMS短信接口定义
│  └─ kits                      # 对应用提供的接口(例如JS接口)
├─ sa_profile                   # 短信服务的启动文件目录
├─ services                     # 短彩信服务实现代码
│  ├─ ims_service_interaction   # IMS短信服务交互层
│  ├─ include                   # 头文件目录
│  ├─ cdma                      # CDMA制式源文件
│  └─ gsm                       # GSM制式源文件
├─ test                         # 单元测试目录
│  ├─ fuzztest                  # 模糊测试相关代码
│  ├─ gtest                     # 自动化测试相关代码
│  └─ unittest                  # 单元测试相关代码
└─ utils                        # 通用工具相关

约束

  • 开发语言:JavaScript。
  • 软件约束,需要与以下服务配合使用:Telephony核心服务(core_service);依赖glib库。
  • 硬件约束,需要搭载的设备支持以下硬件:可以进行独立蜂窝通信的Modem以及SIM卡。

接口说明

表 1 短彩信对外提供的接口

接口名称 接口描述 所需权限
function sendMessage(options: SendMessageOptions): void; 发送短信,通过callback异步获取短信发送结果。 SystemPermission.SEND_MESSAGES
function createMessage(pdu: Array<number>, specification: string, callback: AsyncCallback、<ShortMessage>): void; 根据协议数据单元(PDU)和指定的短信协议创建短信实例,使用callback方式异步返回创建的短信实例。
function createMessage(pdu: Array<number>, specification: string): Promise<ShortMessage> 根据协议数据单元(PDU)和指定的短信协议创建短信实例,使用Promise方式异步返回创建的短信实例。
function getDefaultSmsSlotId(callback: AsyncCallback<number>): void 获取发送短信的默认SIM卡槽,使用callback方式异步返回默认SIM卡槽。
function getDefaultSmsSlotId():Promise<number> 获取发送短信的默认SIM卡,使用Promise方式异步返回默认SIM卡槽。
function getDefaultSmsSimId(callback: AsyncCallback<number>): void 获取发送短信的默认SIM卡ID,使用callback方式异步返回默认SIM卡槽。
function getDefaultSmsSimId():Promise<number> 获取发送短信的默认SIM卡ID,使用Promise方式异步返回默认SIM卡槽。
function setSmscAddr(slotId: number, smscAddr: string, callback: AsyncCallback<void>): void 设置短信服务中心地址,使用callback方式异步返回undefined。 ohos.permission.SET_TELEPHONY_STATE
function setSmscAddr(slotId: number, smscAddr: string): Promise<void> 设置短信服务中心地址,使用Promise方式异步返回undefined。 ohos.permission.SET_TELEPHONY_STATE
function getSmscAddr(slotId: number, callback: AsyncCallback<string>): void 获取短信服务中心地址,使用callback方式异步返回短信服务中心地址。 ohos.permission.GET_TELEPHONY_STATE
function getSmscAddr(slotId: number): Promise<string> 获取短信服务中心地址,使用Promise方式异步返回短信服务中心地址。 ohos.permission.GET_TELEPHONY_STATE

表 2 发送短信接口参数SendMessageOptions说明

参数 类型 描述 是否必填
slotId number 卡槽id
destinationHost string 接收端的电话号码
serviceCenter string 短信中心服务地址
content content | Array<number> 短信内容
destinationPort number 接收端端口号 发送数据短信必填
sendCallback AsyncCallback<ISendShortMessageCallback> 发送结果回调
deliveryCallback AsyncCallback<IDeliveryShortMessageCallback> 送达报告回调

表 3 ISendShortMessageCallback类型说明

参数 类型 描述
result SendSmsResult 发送结果
url string URL地址
isLastPart boolean 是否是最后一条短信

表 4 SendSmsResult枚举值

名称 描述
SEND_SMS_SUCCESS 0 发送成功
SEND_SMS_FAILURE_UNKNOWN 1 发送失败,原因未知
SEND_SMS_FAILURE_RADIO_OFF 2 发送失败,因为Modem关闭
SEND_SMS_FAILURE_SERVICE_UNAVAILABLE 3 发送失败,因为网络不可用

表 5 IDeliveryShortMessageCallback类型说明

参数 类型 描述
pdu Array<number> PDU(Protocol data unit,协议数据单元)数组

表 6 createMessage接口参数说明

参数 类型 描述
pdu Array<number> PDU(Protocol data unit,协议数据单元)数组
specification string 协议类型(3gpp或3gpp2)

表 7 getDefaultSmsSlotId接口参数说明

参数 类型 描述
callback AsyncCallback<number> 回调函数。0:卡槽1:卡槽2

表 8 setSmscAddr接口参数说明

参数名 类型 必填 说明
slotId number SIM卡槽ID:0:卡槽1:卡槽2
smscAddr string 短信服务中心(SMSC)地址。
callback AsyncCallback<void> 回调函数。

表 9 getSmscAddr接口参数说明

参数名 类型 必填 说明
slotId number SIM卡槽ID:0:卡槽1:卡槽2
callback AsyncCallback<string> 回调函数。

表 10 创建短信异步回调ShortMessage说明

变量 类型 说明
emailAddress string 电子邮件地址。
emailMessageBody string 电子邮件正文。
hasReplyPath boolean 收到的短信是否包含“TP-回复路径”,默认为false。“TP-回复路径”:移动电话可循发送SMS消息的短消息中心进行回复。
isEmailMessage boolean 收到的短信是否为电子邮件。
isReplaceMessage boolean 收到的短信是否为“替换短信”,默认为false。“替换短信”有关详细信息,参见 “3GPP TS 23.040 9.2.3.9”。
isSmsStatusReportMessage boolean 当前消息是否为“短信状态报告”,默认为false。“短信状态报告”是一种特定格式的短信,被用来从Service Center到Mobile Station传送状态报告。
messageClass ShortMessageClass 短信类型。
pdu Array<number> SMS消息中的协议数据单元 (PDU)。
protocolId number 发送短信时使用的协议标识。
scAddress string 短信服务中心(SMSC)地址。
scTimestamp number SMSC时间戳。
status number SMS-STATUS-REPORT消息中的短信状态指示短信服务中心(SMSC)发送的短信状态。
userRawData Array<number> 除协议头部的用户数据,即未解码的短信内容。
visibleMessageBody string 短信正文。
visibleRawAddress string 发送者地址。

表 11 getDefaultSmsSimId接口参数说明

参数 类型 描述
callback AsyncCallback<number> 回调函数。

完整的JS API说明以及实例代码请参考:收发短信

使用说明

发送短信

以发送普通文本短信为例,主要步骤和代码如下:

  1. 构造SendMessageOptions对象,传入必要的参数;若关注发送结果或送达报告,需要传入sendCallback或deliveryCallback对象。

  2. 可以通过callback或者Promise的方式调用sendMessage接口。

  3. 该接口为异步接口,相关执行结果会从callback中返回。

    import sms from "@ohos.telephony.sms";
    
    let msg: SendMessageOptions = {
      slotId: 0,
      destinationHost: '123xxxxxxxx',
      content: '这是一封短信',
      sendCallback: (err, data) => {
        if (err) {
          // 接口调用失败,err非空
          console.error(`failed to send message because ${err.message}`);
          return;
        }
        // 接口调用成功,err为空
        console.log(`success to send message: ${data.result}`);
      }
    }
    
    // 调用接口
    sms.sendMessage(msg);

创建ShortMessage对象

以解析3gpp类型的PDU,调用createMessage为例,主要步骤和代码如下:

  1. 构造短信的PDU,指定协议类型为3gpp或者3gpp2。

  2. 可以通过callback或者Promise的方式调用createMessage接口。

  3. 该接口为异步接口,成功后获取ShortMessage 对象属性来得到解析后的短信息数据。

    import sms from "@ohos.telephony.sms";
    
    let pdu = [80, 80, 80]; // 这里只是表示是短信PDU,并非真实短信
    let specification = "3gpp";
    
    // 调用接口【callback方式】
    sms.createMessage(pdu, specification, (err, value) => {
      if (err) {
        // 接口调用失败,err非空
        console.error(`failed to createMessage because ${err.message}`);
        return;
      }
      // 接口调用成功,err为空
      console.log(`success to createMessage: ${value}`);
    });
    
    // 调用接口【Promise方式】
    let promise = sms.createMessage(pdu, specification);
    promise.then((value) => {
      // 接口调用成功,此处可以实现成功场景分支代码。
      console.log(`success to createMessage: ${value}`);
    }).catch((err) => {
      // 接口调用失败,此处可以实现失败场景分支代码。
      console.error(`failed to createMessage because ${err.message}`);
    });

发送彩信

以中国联通SIM卡发送彩信为例,主要步骤和代码如下:

  1. 发送彩信,需要先编码再发送。

  2. 编码:将多媒体文件编码成彩信pdu。app将多媒体文件放入沙箱,调用编码接口encodeMms,app传入必要参数,返回的彩信pdu需要app写入沙箱

  3. 发送:将彩信pdu发送到对端手机。调用发送接口sendMms,app需传入必要参数,彩信中心需和运营商卡匹配。

  4. 可以通过callback或者Promise的方式调用sendMessage接口。

  5. 该接口为异步接口,相关执行结果会从callback中返回。

    import mms from "@ohos.telephony.sms";
    
    // 获取MmsType,输入本机号码,目的手机号码
    async function getMmstype(tid){
      return {
        from : {address: '+86xxxxxxxxxxx/TYPE=PLMN', charset: mms.UTF_8},
        to: [{address: '+86xxxxxxxxxxx/TYPE=PLMN', charset: mms.UTF_8}],
        contentType: "application/vnd.wap.multipart.related",
        transactionId: tid,
        version: mms.MMS_VERSION_1_2,
        subject: "Test mms"
      };
    }
    let MMSTYPE = await getMmstype("1");
    
    // 只包括图片附件,图片名字picture.gif
    const ATTACHMENT_PICTURE = [
      {path: sandPath + 'picture.gif',
        fileName: 'picture.gif',
        contentId:'<picture.gif>',
        contentLocation:'picture.gif',
        contentDisposition: mms.ATTACHMENT,
        contentTransferEncoding: 'binary',
        contentType:'image/gif',
        isSmil: false,
        inBuff: [],
        charset: mms.UTF_8
      }
    ];
    
    // 编码彩信pdu
    const wrapperStepForEncodeMms = async function (mmsType, attachment) {
      try {
        // 调用编码接口
        const encodeData = await mms.encodeMms({messageType: mms.TYPE_MMS_SEND_REQ, mmsType, attachment});
        console.log(`encodeMms Success, data length:${encodeData.length}`);
        await writefd(casename, encodeData);
      } catch (error) {
        throw error;
      }
    };
    
    // 进行彩信pdu编码,编码前将图片放入沙箱
    try {
      await wrapperStepForEncodeMms(MMSTYPE, ATTACHMENT_PICTURE);
      console.log(`wrapperStepForEncodeMms success.`);
    } catch (error) {
      console.log(`wrapperStepForEncodeMms fail, error: ${toString(error)}`);
      return;
    }
    
    const sandBoxPath = '/data/storage/el2/base/files/';
    let filePath  = sandBoxPath + 'SendReq.mms';
    // 彩信pdu写入沙箱
    async function writefd(array){
      let data = new Uint8Array(array).buffer;
      try {
        let fd = await fileio.open(filePath , 0o102, 0o666);
        console.log(`fd: ${toString(fd)}`);
        const number = await fileio.write(fd, data);
        console.log(`write data to file success number: ${toString(number)}`);
        await fileio.close(fd);
      } catch (error) {
        console.log(`write data to file failed with error: ${toString(error)}`);
      }
    }
    
    // 彩信用户代理、用户代理描述配置。根据运营商要求配置,默认ua,uaprof
    let mmsCfg = {
      userAgent:'ua',
      userAgentProfile: 'uaprof'
    };
    
    // 发送彩信参数
    let mmsParams = {
      slotId : DEFAULT_SLOTID,
      mmsc: 'http://mmsc.myuni.com.cn',
      data: filePath,
      mmsConfig: mmsCfg
    };
    // 调用发送接口
    mms.sendMms(globalThis.context, mmsParams, async(err) =>{
      if (err) {
        console.log(`sendMms fail, err : ${toString(err)}`);
        return;
      }
      console.log(`sendMms Success`);
    }

相关仓

电话服务子系统

telephony_sms_mms

telephony_core_service

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS

简介

Providing SMS and MMS functions | 负责短彩信相关功能 展开 收起
C++ 等 2 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/openharmony/telephony_sms_mms.git
git@gitee.com:openharmony/telephony_sms_mms.git
openharmony
telephony_sms_mms
telephony_sms_mms
master

搜索帮助

14c37bed 8189591 565d56ea 8189591