首先声明一个类,此类继承自BroadcastReceiver类,处理Android当中发出的广播事件:
public class SMSReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("MyDebug", "SendMessage");
//接收Intent对象当中的数据,获得发送短信的内容
Bundle bundle = intent.getExtras();
//在Bundle对象当中有一个属性名为pdus,这个属性的值是一个Object数组
Object[] myOBJpdus = (Object[])bundle.get("pdus");
//创建一个SmsMessage类型的数组
SmsMessage[] messages = new SmsMessage[myOBJpdus.length];
for(int i =0;i<myOBJpdus.length;i++){
//使用Object数组当中的对象创建SmsMessage对象
messages[i] = SmsMessage.createFromPdu((byte[])myOBJpdus[i]);
Log.d("MyDebug", messages[i].getDisplayMessageBody());
}
}
在AndroidManifest.xml文件中静态定义SMSReceiver类接收Android的接收到短信广播事件:
<receiver android:name=".SMSReceiver">
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
要想触发短信接收广播事件,应在AndroidManifest.xml中首先声明响应的权限:
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
在代码中定义接收到短信广播事件处理:
private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
SMSReceiver smsReceiver = new SMSReceiver(); //生成一个BroadCastReceiver对象
//生成一个IntentFilter对象
IntentFilter filter = new IntentFilter();
filter.addAction(SMS_ACTION);
OtherActivity.this.registerReceiver(smsReceiver, filter);
在代码中解除对事件的接收到短信广播的绑定:
OtherActivity.this.unregisterReceiver(smsReceiver);