安卓动态注册广播

如何动态注册广播:
1。首先定义一个广播接收器:
public class cotentReceiver extends BroadcastReceiver {
public static String strAction = “aaa”;//定义的广播1的Action
public static String myAction = “bbb”;//定义的广播2的Action

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, intent.getAction(), 1).show();
    if (strAction.equals(intent.getAction())) {
        Toast.makeText(context,
                "广播1", 1)
                .show();
    } else if (myAction.equals(intent.getAction())) {
        Toast.makeText(context, "广播2", 1).show();
    }

}

}
2.Activity里动态注册广播
public class MainActivity extends Activity implements OnClickListener {

private cotentReceiver cotent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myregister();//动态注册广播
    setContentView(R.layout.activity_main);
    Button b1 = (Button) findViewById(R.id.bt_1);
    Button b2 = (Button) findViewById(R.id.bt_2);
    Button b3 = (Button) findViewById(R.id.bt_3);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);
}
//动态注册广播
private void myregister() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(cotentReceiver.strAction);//广播1的Action
    intentFilter.addAction(cotentReceiver.myAction);//广播2的Action
    cotent = new cotentReceiver();//new出一个广播接受器
    registerReceiver(cotent, intentFilter);//注册广播
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.bt_1:
        seng1();//发出广播1的广播
        break;
    case R.id.bt_2:
        seng2();//发出广播2的广播
        break;

    default:
        break;
    }
}

private void seng2() {
    Intent in = new Intent();
    in.setAction(cotentReceiver.myAction);
    sendBroadcast(in);
}

private void seng1() {
    Intent intent = new Intent();
    intent.setAction(cotentReceiver.strAction);
    sendBroadcast(intent);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unmyregister();//取消注册广播
}

//取消注册广播
private void unmyregister() {
unregisterReceiver(cotent);
}

}
说明:动态注册广播记得在Activity的onDestroy生命周期里取消注册,不然会报错,动态注册广播不需要在配置清单文件里注册,清单文件里不需要写什么东西,因为我们已经在代码里注册了

本人个人项目地址:百度搜索安卓应用—-点击进入百度应用市场—搜索”电话老人版”

你可能感兴趣的:(安卓)