欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android编程实现短信收发及语音播报提示功能示例

程序员文章站 2023-12-02 18:58:16
本文实例讲述了android编程实现短信收发及语音播报提示功能。分享给大家供大家参考,具体如下: 发送短信功能界面 /** * 发送短信demo *...

本文实例讲述了android编程实现短信收发及语音播报提示功能。分享给大家供大家参考,具体如下:

发送短信功能界面

/**
 * 发送短信demo
 *
 * @description:
 * @author ldm
 * @date 2016-4-22 上午9:07:53
 */
public class smsactivity extends activity implements onclicklistener {
  public static final string sms_recipient_extra = "com.ldm.study.sms_recipient";
  public static final string action_sms_sent = "com.ldm.study.sms_sent_action";
  private button sms_send_message;
  private edittext sms_recipient;
  private edittext sms_content;
  private checkbox sms_enable_receiver;
  private textview sms_status;
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.send_sms_layout);
    initviews();
    initlisteners();
    registersmsreceiver();
  }
  /**
   * 注册短信监听广播
   *
   * @description:
   * @author ldm
   * @date 2016-4-22 上午9:23:23
   */
  private void registersmsreceiver() {
    registerreceiver(new broadcastreceiver() {
      @override
      public void onreceive(context context, intent intent) {
        string message = null;
        boolean error = true;
        switch (getresultcode()) {
        case activity.result_ok:
          message = "发送成功!";
          error = false;
          break;
        case smsmanager.result_error_generic_failure:
          message = "发送失败";
          break;
        case smsmanager.result_error_no_service:
          message = "发送失败";
          break;
        case smsmanager.result_error_null_pdu:
          message = "发送失败";
          break;
        case smsmanager.result_error_radio_off:
          message = "发送失败";
          break;
        }
        sms_recipient.setenabled(true);
        sms_content.setenabled(true);
        sms_content.settext("");
        sms_status.settext(message);
        sms_status.settextcolor(error ? color.red : color.green);
      }
    }, new intentfilter(action_sms_sent));
  }
  /**
   * 监听事件
   *
   * @description:
   * @author ldm
   * @date 2016-4-22 上午9:24:20
   */
  private void initlisteners() {
    sms_send_message.setonclicklistener(this);
    // 应用package管理器
    final packagemanager pm = this.getpackagemanager();
    // 获取到应用中指定的组件
    final componentname componentname = new componentname("com.ldm.study",
        "com.ldm.study.receiver.smsmessagereceiver");
    // 根据组件是否可用的状态来判断sms_enable_receiver的选中状态
    sms_enable_receiver
        .setchecked(pm.getcomponentenabledsetting(componentname) == packagemanager.component_enabled_state_enabled);
    // 监听sms_enable_receiver设置广播组件是否可用
    sms_enable_receiver
        .setoncheckedchangelistener(new oncheckedchangelistener() {
          public void oncheckedchanged(compoundbutton buttonview,
              boolean ischecked) {
            // 组件状态设置
            pm.setcomponentenabledsetting(
                componentname,
                ischecked ? packagemanager.component_enabled_state_enabled
                    : packagemanager.component_enabled_state_disabled,
                packagemanager.dont_kill_app);
          }
        });
  }
  private void initviews() {
    sms_recipient = (edittext) (findviewbyid(r.id.sms_recipient));
    sms_content = ((edittext) findviewbyid(r.id.sms_content));
    // 是否打开短信广播接收开关
    sms_enable_receiver = (checkbox) findviewbyid(r.id.sms_enable_receiver);
    sms_send_message = (button) findviewbyid(r.id.sms_send_message);
    sms_status = (textview) findviewbyid(r.id.sms_status);
    if (getintent().hasextra(sms_recipient_extra)) {
      sms_recipient.settext(getintent().getextras().getstring(
          sms_recipient_extra));
      sms_content.requestfocus();
    }
  }
  @override
  public void onclick(view v) {
    if (v.getid() == r.id.sms_send_message) {
      sendsms();
    }
  }
  /**
   * 发送短信
   *
   * @description:
   * @author ldm
   * @date 2016-4-22 上午9:30:38
   */
  private void sendsms() {
    if (textutils.isempty(sms_recipient.gettext())) {
      toast.maketext(smsactivity.this, "请输入短信接收者", toast.length_short)
          .show();
      return;
    }
    if (textutils.isempty(sms_content.gettext())) {
      toast.maketext(smsactivity.this, "请输入短信内容", toast.length_short)
          .show();
      return;
    }
    sms_recipient.setenabled(false);
    sms_content.setenabled(false);
    smsmanager sms = smsmanager.getdefault();
    list<string> messages = sms.dividemessage(sms_recipient.gettext()
        .tostring());
    string recipient = sms_content.gettext().tostring();
    for (string message : messages) {
      // 发送短信
      sms.sendtextmessage(recipient, null, message, pendingintent
          .getbroadcast(smsactivity.this, 0, new intent(
              action_sms_sent), 0), null);
    }
  }
}

收到短信后处理界面:

/**
 * 接收短信语音播报
 *
 * @description:
 * @author ldm
 * @date 2016-4-22 上午9:34:21
 */
public class smsreceivedactivity extends activity implements oninitlistener {
  private static final int dialog_show_message = 1;
  public static final string sms_from_address_extra = "com.ldm.study.sms_from_address";
  public static final string sms_from_display_name_extra = "com.ldm.study.sms_from_display_name";
  public static final string sms_message_extra = "com.ldm.study.sms_message";
  private texttospeech mtts;
  private string mfromdisplayname;
  private string mfromaddress;
  private string mmessage;
  private string mfullbodystring;
  @suppresswarnings("deprecation")
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    // 短信来电号码
    mfromaddress = getintent().getextras()
        .getstring(sms_from_address_extra);
    // 来电人称呼
    mfromdisplayname = getintent().getextras().getstring(
        sms_from_display_name_extra);
    mmessage = getintent().getextras().getstring(sms_message_extra);
    // 短信内容
    mfullbodystring = string.format(getstring(r.string.sms_format),
        mfromdisplayname, mmessage);
    showdialog(dialog_show_message);
    //初始化tts
    mtts = new texttospeech(this, this);
  }
  /**
   * 初始化tts服务
   */
  @suppresswarnings("deprecation")
  public void oninit(int status) {
    if (status == texttospeech.success) {// 成功状态
      // 设置语言,tts引擎支持 english、 french 、 german 、 italian 和 spanish 这5大语言
      int result = mtts.setlanguage(locale.english);
      if (result == texttospeech.lang_missing_data
          || result == texttospeech.lang_not_supported) {
        toast.maketext(this, "tts不可用", toast.length_long).show();
      } else {
        mtts.speak(mfullbodystring, texttospeech.queue_add, null);
        // mtts.speak(mfullbodystring, texttospeech.queue_add, null,
        // "");
      }
    } else {
      toast.maketext(this, "tts初始化失败", toast.length_long).show();
    }
  }
  @override
  protected dialog oncreatedialog(int id) {
    switch (id) {
    case dialog_show_message:
      return new alertdialog.builder(this)
          .seticon(android.r.drawable.ic_dialog_email)
          .settitle("message received")
          .setmessage(mfullbodystring)
          .setpositivebutton("回复",
              new dialoginterface.onclicklistener() {
                public void onclick(dialoginterface dialog,
                    int whichbutton) {
                  // 回复短信则跳转到发送短信界面,把接收人信息带过去
                  intent i = new intent();
                  i.setclass(smsreceivedactivity.this,
                      smsactivity.class);
                  i.putextra(smsactivity.sms_recipient_extra,
                      mfromaddress);
                  startactivity(i);
                  dialog.dismiss();
                  finish();
                }
              })
          .setnegativebutton("取消",
              new dialoginterface.onclicklistener() {
                public void onclick(dialoginterface dialog,
                    int whichbutton) {
                  dialog.dismiss();
                  finish();
                }
              }).create();
    }
    return null;
  }
}

短信广播

/**
 * 短信来信监听广播
 *
 * @description:
 * @author ldm
 * @date 2016-4-22 上午10:07:49
 */
public class mymsmreceiver extends broadcastreceiver {
  @override
  public void onreceive(context context, intent intent) {
    bundle extras = intent.getextras();
    if (extras == null)
      return;
    // 收到的短信内容
    object[] pdus = (object[]) extras.get("pdus");
    for (int i = 0; i < pdus.length; i++) {
      smsmessage message = smsmessage.createfrompdu((byte[]) pdus[i]);
      string fromaddress = message.getoriginatingaddress();
      string fromdisplayname = fromaddress;
      uri uri;
      string[] projection;
      uri = uri.withappendedpath(
          contactscontract.phonelookup.content_filter_uri,
          uri.encode(fromaddress));
      projection = new string[] { contactscontract.phonelookup.display_name };
      // 查询短信的发件人
      cursor cursor = context.getcontentresolver().query(uri, projection,
          null, null, null);
      if (cursor != null) {
        if (cursor.movetofirst())
          fromdisplayname = cursor.getstring(0);
        cursor.close();
      }
      // 跳转到短信接收界面
      intent di = new intent();
      di.setclass(context, smsreceivedactivity.class);
      di.addflags(intent.flag_activity_new_task
          | intent.flag_activity_single_top);
      di.putextra(smsreceivedactivity.sms_from_address_extra, fromaddress);
      di.putextra(smsreceivedactivity.sms_from_display_name_extra,
          fromdisplayname);
      di.putextra(smsreceivedactivity.sms_message_extra, message
          .getmessagebody().tostring());
      context.startactivity(di);
    }
  }
}

附:demo示例代码点击此处本站下载

更多关于android相关内容感兴趣的读者可查看本站专题:《android短信与电话操作技巧汇总》、《android文件操作技巧汇总》、《android操作json格式数据技巧总结》、《android编程之activity操作技巧总结》、《android开发入门与进阶教程》、《android资源操作技巧汇总》、《android视图view技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。