Android通过广播接收短信

来源:互联网 发布:淘宝免费刷流量软件 编辑:程序博客网 时间:2024/06/05 11:09
public class MySMS extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent intent) {        if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){            Log.i("test","收到短信了");            Bundle bundle=intent.getExtras();//得到intent对象            Object[] objects= (Object[]) bundle.get("pdus");//构建短信对象            SmsMessage[] messages=new SmsMessage[objects.length];//根据收到的对象创建长度            //根据收到的对象长度创建objects长度            for (int i = 0; i < objects.length; i++) {                //把每一个单元的pdu格式的短信转换成SmsMessage对象                messages[i] = SmsMessage.createFromPdu((byte[]) objects[i]);            }            for (SmsMessage message : messages) {                //获取对方的手机号码                String address=message.getOriginatingAddress();                //获取短信的内容                String body=message.getDisplayMessageBody();                Log.i("test",address+":"+body);            }        }    }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.zking.y2_android22_sms">    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"        android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true" android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver android:name=".MySMS">            <intent-filter>                <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>            </intent-filter>        </receiver>    </application></manifest>