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下载地址:http://download.csdn.net/detail/true100/9498881

时间: 2024-10-13 11:35:50

Android短信收到,语音播报的相关文章

Android短信彩信收发流程(应用层)

下图为ComposeMessageActivity中confirmSendMessageIfNeeded部分的信息发送流程.主要以接收者有效性的确认为主,然后转向sendMessage方法进行发送. ComposeMessageActivity.sendMessage从下图可以看出,在这个方法中,主要做的事是确认手机状态的有效性.最终调用WorkingMessage的send方法进行信息的发送.  WorkingMessage.send从下图可以看出,在本方法中,对于不同类型的消息,分别调用不同

Android短信监听(三)——利用Loader实现短信监听

MainActivity如下: package cc.c; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.app.LoaderManager.LoaderCallbacks; import android.content.Context; import android.content.Loader; import android.database.Curs

Android短信监听(二)——利用ContentObserver实现短信监听

MainActivity如下: package cc.testsmslistener; import cc.testsmslistener.SMSContentObserver.MessageListener; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; import android.app.Activity; /** *

Android短信数据库监听回调多次问题

在监听Android短信数据库变化时.由于只能注册content://sms/ 的observer.所以,在数据库每次状态变化的时候,都会多次回调onChange 方式.目前还未找到很好的方式,解决回调多次的问题.只能通过代码逻辑来屏蔽这个问题. 目前,我使用的方式是通过时间来过滤两次的回调. long lastTimeofCall = 0L;    long lastTimeofUpdate = 0L;    long threshold_time = 10000; if (lastTimeo

Android短信监听(一)——利用BroadcastReceiver实现短信监听

MainActivity如下: package cc.testsmsbroadcastreceiver; import cc.testsmsbroadcastreceiver.SMSBroadcastReceiver.MessageListener; import android.os.Bundle; import android.widget.TextView; import android.app.Activity; /** * Demo描述: * 利用BroadcastReceiver实现

Android -- 短信

背景                                                                                           主要代码                                                                                      发送按钮的监听器: phone_number_editText = (EditText) findViewById(R.id.phon

初识安卓小程序(Android短信发送器)

首先,先创建一个安卓项目(我的版本是4.4.2的),名字为"短信发送器" 然后在res文件夹下找到layout文件夹,找到activity_main.xml或fragment_main.xml,在里面输入或拖拽按钮 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tool

Android短信插入器源码

package com.examp.createsms; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import android.os.Bundle; public class MainActivity extends Activity { @Override protected

Android 短信的还原

上篇文章讲到<Android 短信的备份>,本文主要实现Android 短信的还原,即是将一条 布局文件: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" andr