publicclass AReceiver extends BroadcastReceiver {
public AReceiver() {
// TODO Auto-generated constructor stub
System.out.println("AReceive---->Constructor");
}
@Override
publicvoid onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("The TimeZone Changed");
}
}
<receiverandroid:name=".AReceiver">
<intent-filter>
<actionandroid:name="android.intent.action.TIMEZONE_CHANGED"></action>
</intent-filter>
</receiver>
<uses-permissionandroid:name="android.permission.RECEIVE_SMS"/>
publicclass BroadcastDemo2Activity extends Activity {
//有两个按钮,分别是注册广播接收器和注销广播接收器
private Button button_register = null;
private Button button_unregister = null;
private AReceiver aReceiver = null;
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button_register = (Button)findViewById(R.id.register);
button_unregister = (Button)findViewById(R.id.unregister);
button_register.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View arg0) {
// TODO Auto-generated method stub
aReceiver = new AReceiver(); //创建一个BroadcastReceiver的子类的对象,然后我们就要对他进行设置了
IntentFilter intentFilter = new IntentFilter();//创建一个IntentFilter的对象,这就和上个例子中的intent-filter标签一样,我们要往里面添加过滤器
intentFilter.addAction("android.intent.action.TIMEZONE_CHANGED");//同样,我们添加和上一个例子一样的intent action,用来接收当时区改变的消息
BroadcastDemo2Activity.this.registerReceiver(aReceiver, intentFilter);//添加完过滤器后,就要将BroadcastReceiver对象和相应的过滤器注册在Activity上
}
});
button_unregister.setOnClickListener(new OnClickListener() {
@Override
publicvoid onClick(View arg0) {
// TODO Auto-generated method stub
BroadcastDemo2Activity.this.unregisterReceiver(aReceiver);//注销BroadcastReceiver的注册
}
});
}
}
附件为两个例子的参考代码,仅供参考。
如果我的文章给与了你帮助,就不妨请我喝杯咖啡吧,点击->