第一步先定义一个class类
package com.example.g160628_android22; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.util.Log; /** * Created by Administrator on 2017/7/13. */ 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(); Object object[]= (Object[]) bundle.get("pdus"); SmsMessage smsMessage[]=new SmsMessage[object.length]; for (int i = 0; i < object.length; i++) { smsMessage[i]=SmsMessage.createFromPdu((byte[])object[i]); } for (SmsMessage message : smsMessage) { String address=message.getOriginatingAddress(); String body=message.getDisplayMessageBody(); Log.i("test",address+":"+body); } } } }
第二步:
在XML中配置
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.g160628_android22">
<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>