zoukankan      html  css  js  c++  java
  • (十六)短信广播接收

    一、需求:当接收到短信到来的广播的时候,获得短信的内容和发件人

    二、SmsReceiver.java文件如下所示:

    package com.example.smslistenerreiceiver;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.SmsMessage;
    import android.telephony.gsm.SmsManager;
    import android.util.Log;
    
    public class SmsReceiver extends BroadcastReceiver {
    
        private static final String TAG = "SmsReceiver";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.i(TAG, "短信来了");
            Object [] pdus = (Object[]) intent.getExtras().get("pdus");
            
            for(Object pdu :pdus){
                SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
                String sender = sms.getOriginatingAddress();
                String body = sms.getMessageBody();
                Log.i(TAG, "发件人:"+sender);
                Log.i(TAG, "短信内容:"+body);
                
                if("5566".equals(sender)){
                    SmsManager sm = SmsManager.getDefault();
                    sm.sendTextMessage(sender, null, "短信", null, null);
                }
            }
        }
    }

    三、注意添加接收短信的权限

     <uses-permission android:name="android.permission.RECEIVE_SMS" />

    四、注册监听广播事件

    <receiver android:name=".SmsReceiver" >
                <intent-filter android:priority="2147483647" >
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                </intent-filter>
            </receiver>
  • 相关阅读:
    20210312
    20210311
    20210310
    例5-1
    例5-2
    例4-12-2
    例4-12
    例4-11
    例4-10
    例4-9
  • 原文地址:https://www.cnblogs.com/fuyanan/p/4093412.html
Copyright © 2011-2022 走看看