首页 > 代码库 > Android中广播的简单使用

Android中广播的简单使用

//注册本地广播接受者
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//接收到广播做出的操作
}
};
broadcastManager.registerReceiver(mReceiver, intentFilter);
 
 
 
//发送广播
Intent intent = new Intent("test");
Bundle bundle = new Bundle();
bundle.putInt("msgNum", sum);
intent.putExtras(bundle);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
 
 
 
@Override
public void onDestroy() {
super.onDestroy();
//注销广播,释放资源
broadcastManager.unregisterReceiver(mReceiver);
}

 

Android中广播的简单使用