亲宝软件园·资讯

展开

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

迟做总比不做强 人气:0
想了解Android编程实现短信收发及语音播报提示功能示例的相关内容吗,迟做总比不做强在本文为您仔细讲解Android短信收发及语音播报提示的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,短信收发,语音播报,提示,下面大家一起来学习吧。

本文实例讲述了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程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论