码迷,mamicode.com
首页 > 移动开发 > 详细

Android短信收发(二)

时间:2017-09-25 16:08:52      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:ted   rtb   cti   note   ati   ges   context   telephony   not   

接收SMS类,代码如下

//for receive SMS
    private SmsReceiver mSmsReceiver;
    @Override
    protected void onResume() {
        super.onResume();
        mSmsReceiver = new SmsReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        intentFilter.setPriority(1000);
        registerReceiver(mSmsReceiver, intentFilter);
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mSmsReceiver);
    }
    public class SmsReceiver extends BroadcastReceiver {
        public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG,"action: "+action);
            if (SMS_RECEIVED_ACTION.equals(action)) {
                Bundle bundle = intent.getExtras();

                //String messageContent = bundle.getString("message");
                Object[] pdus = (Object[]) bundle.get("pdus");//获取短信数组
                SmsMessage[] messages = new SmsMessage[pdus.length];
                String format = intent.getStringExtra("format");
                for (int i = 0; i < messages.length; i++) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i],format);//将pdu字符数组转换成SmsMessage对象
                    }
                    else {
                        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    }
                }
                String address = messages[0].getOriginatingAddress();//获取短信发送方的号码
                String fullMessage = "";
                for (SmsMessage message : messages) {
                    fullMessage += message.getMessageBody();//获取短信的内容
                }
                //sender.setText(address);
                //content.setText(fullMessage);
                Log.d(TAG,"SMS notes: "+fullMessage);
                abortBroadcast();
            }
        }
    }

  

Android短信收发(二)

标签:ted   rtb   cti   note   ati   ges   context   telephony   not   

原文地址:http://www.cnblogs.com/eniac1946/p/7592024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!