Android 广播 BroadcastReceiver 动态注册

Android 广播 BroadcastReceiver 动态注册

// dynamicReceiver
DynamicReceiver dynamicReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    // 动态广播BroadcastReceiver
    // 实例化IntentFilter对象
    IntentFilter filter = new IntentFilter();
    filter.addAction("cts_bcr");
    dynamicReceiver = new DynamicReceiver();
    // 注册广播接收
    registerReceiver(dynamicReceiver,filter);
}

// 通过继承 BroadcastReceiver建立动态广播接收器
class DynamicReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast toast = Toast.makeText(context,"动态广播:"+ intent.getStringExtra("cts_bcr_msg"), Toast.LENGTH_SHORT);
        // 设置弹出位置
        toast.setGravity(Gravity.TOP,0,0);
        toast.show();
    }
}

// 动态注册需在Acticity生命周期onPause通过unregisterReceiver()方法移除广播接收器,优化内存空间,避免内存溢出
@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(dynamicReceiver);
}

// 发送测试
btnOK.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setAction("cts_bcr");
        intent.putExtra("cts_bcr_msg","cts_bcr_msg 测试");
        sendBroadcast(intent);
    } 
}

 

发表回复

您的电子邮箱地址不会被公开。