android 动态注册广播

1注册广播

private  BroadcastReceiver MyBroadcastReceiver = null;
 IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("MainBroadcast");
        MyBroadcastReceiver=new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                // TODO Auto-generated method stub
                Log.i("aa", "接受到广播");
               String type=arg1.getStringExtra("type");
                if(type.equals("logOff"))
                {
                   //todo
                }

            }
        };
  registerReceiver(MyBroadcastReceiver,intentFilter); //注册监听
PS:记得在合适的地方取消简体

unregisterReceiver(MyBroadcastReceiver); //取消监听
2发送广播

Log.i("aa", "发送广播");
  Intent intent = new Intent("MainBroadcast");
  intent.putExtra("type", "logOff");
  sendBroadcast(intent);//传递过去

你可能感兴趣的:(android 动态注册广播)