1、定义一个类 SMSReceiver 继承 BroadcastReceiver 。并在清单文件中注册:
<receiver android:name="com.example.CallMe.Receiver.SMSReceiver" >在注册的过程中,可将优先级设为最高:
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<receiver android:name="com.example.CallMe.Receiver.SMSReceiver" >2、在 onReceive 方法中获得短信的发送者,可短信内容:
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
public void onReceive(Context context, Intent intent) {如果想让自己的应用接收到短信后,不让手机接收到广播,可终止广播:abortBroadcast();
// TODO Auto-generated method stub
// 获得短信数组,pdus为短信协议
Object[] objs = (Object[]) intent.getExtras().get("pdus");
// 遍历数组,创建短信
for (Object obj : objs) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
// 获得短信发送者和短信内容
String sender = smsMessage.getOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
}
}