用Broadcast Receiver刷新数据(二)
采用消息发布/订阅的一个很大的优点就是代码的简洁性,并且能够有效地降低消息发布者和订阅者之间的耦合度。
举个例子,比如有两个界面,ActivityA和ActivityB,从ActivityA界面跳转到ActivityB界面后,ActivityB要给ActivityA发送一个消息,ActivityA收到消息后在界面上显示出来。我们最先想到的方法就是使用广播,使用广播实现此需求的代码如下:
首先需要在ActivityA中定义一个广播接收器:
public class MessageBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
mMessageView.setText("Message from SecondActivity:" + intent.getStringExtra("message"));
}
}
还需要在onCreate()方法中注册广播接收器:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册事件
EventBus.getDefault().register(this);
//注册广播
IntentFilter intentFilter = new IntentFilter("message_broadcast");
mBroadcastReceiver = new MessageBroadcastReceiver();
registerReceiver(mBroadcastReceiver, intentFilter);
......
}
然后在onDestory()方法中取消注册广播接收器:
@Override
protected void onDestroy() {
super.onDestroy();
......
//取消广播注册
unregisterReceiver(mBroadcastReceiver);
}
最后我们需要在ActivityB界面中发送广播消息:
findViewById(R.id.send_broadcast).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = mMessageET.getText().toString();
if(TextUtils.isEmpty(message)) {
message = "defaule message";
}
Intent intent = new Intent();
intent.setAction("message_broadcast");
intent.putExtra("message", message);
sendBroadcast(intent);
}
});