①注册广播事件:
注册方式有两种,
一种是静态注册,就是在AndroidManifest.xml文件中定义,注册的广播接收器必须要继承BroadcastReceiver;
另一种是动态注册,是在程序中使用Context.registerReceiver注册,注册的广播接收器相当于一个匿名类。两种方式都需要IntentFIlter。
②发送广播事件:通过Context.sendBroadcast来发送,由Intent来传递注册时用到的Action。
③接收广播事件:当发送的广播被接收器监听到后,会调用它的onReceive()方法,并将包含消息的Intent对象传给它。onReceive中代码的执行时间不要超过5s,否则Android会弹出超时dialog。
Intent intent = new Intent();
-
Intent intent = new Intent();
intent.setAction("SENDRECEIVE");
sendBroadcast(intent);//有序广播
//sendOrderedBroadcast(intent,null,new MyReceiver(),null,"发送的内容");无序广播
IntentFilter filter_system = new IntentFilter();
- filter_system.addAction(SYSTEMACTION);
- registerReceiver(systemReceiver, filter_system);
- }
- private BroadcastReceiver dynamicReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.e("MainActivity", "接收自定义动态注册广播消息");
- if(intent.getAction().equals(DYNAMICACTION)){
- String msg = intent.getStringExtra("msg");
- Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
- }
- }
- };
- private BroadcastReceiver systemReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.e("MainActivity", "接收系统动态注册广播消息");
- if(intent.getAction().equals(SYSTEMACTION)){
- String msg = intent.getStringExtra("msg");
- Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
- }
- }
- };
- }
//发送广播刷新用户数据
Intent intent = new Intent();
intent.setAction(MyFragment.FILTER_CODE);
sendBroadcast(intent);
mContext.sendBroadcast(new Intent().setAction("home"));//发送广播刷新首页商品
//注册广播
IntentFilter filter = new IntentFilter("home");
mContext.registerReceiver(new MyReceiver(), filter);
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//位置信息
tvLocation.setText("");
loadingDialog.show();
//启动定位
mLocationClient.startLocation();
}
}