注册BroadcastReceiver的方法有两种:
1、在应用程序的代码中进行注册
如果一个BroadcastReceiver用于更新UI,那么通常会使用这种方法进行注册
在Activity启动的时候注册BroadcastReceiver,在Activity不可见以后取消注册
注册BroadcastReceiver: registerReceiver(receiver,filter);
取消注册BroadcastReceiver: unregisterReceiver(receiver);
2、在AndroidManifest.xml当中进行注册
使用这样的方式注册BroadcastReceiver,即使应用程序没有启动,或者被kill掉后,也始终会处于活动状态, BroadcastReceiver还可以接收广播消息
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="android.intent.action.PICK" />
</intent-filter>
</receiver>
例程:在应用程序的代码中进行注册:
TestBC2Activity.java
public class TestBC2Activity extends Activity {
private Button registerButton = null;
private Button unregisterButton = null;
private SMSReceiver smsReceiver = null;
private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerButton = (Button)findViewById(R.id.register);
unregisterButton = (Button)findViewById(R.id.unregister);
registerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//生成一个BroiadcastReceiver对象
smsReceiver = new SMSReceiver();
//生成一个IntentFilter对象
IntentFilter filter = new IntentFilter();
//为IntentFilter添加一个Action
filter.addAction(SMS_ACTION);
//将BroadcastReceiver对象注册到系统当中
TestBC2Activity.this.registerReceiver(smsReceiver,filter);
}
});
unregisterButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//解除BroadcastReceiver对象的注册
TestBC2Activity.this.unregisterReceiver(smsReceiver);
}
});
}
}
SMSReceiver.java
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("receive message");
//接受Intent对象当中的数据
Bundle bundle = intent.getExtras();
//在Bundle对象当中有一个属性名为pdus,这个属性的值是一个Object数组
Object[] myOBJpdus = (Object[]) bundle.get("pdus");
//创建一个SmsMessage类型的数组
SmsMessage[] message = new SmsMessage[myOBJpdus.length];
System.out.println(message.length);
for(int i = 0 ; i < myOBJpdus.length; i++){
//使用Object数组当中的对象创建SmsMessage对象
message[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);
//调用SmsMessage对象的getDisppalyMessageBody()方法,就可以得到消息的内容
System.out.println(message[i].getDisplayMessageBody());
}
}
}
这个广播接收是测试接收短信,所以需要mainfest文件允许
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
先按“register”按钮,注册BroadcastReceiver,即绑定监听器,然后再给模拟发短信
结果:
备注:
给模拟器发短信是使用Emulator Control