当一个Android应用功能越来越多的时候,保证应用的各个部分之间高效的通信将变得越来越困难。如何优雅地解决这个问题?这时候,就需要使用到EventBus。
EventBus是GreenRobot出品的Android系统的一个Event Bus类库,使用起来和之前我们所介绍的Square的Otto差不多,都是用来简化应用组件之间的通信。
安装
1 使用gradle
1
2
3
|
dependencies {
compile
'de.greenrobot:eventbus:2.2.1'
}
|
2使用 maven
1
2
3
4
5
|
<dependency>
<groupId>de.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>
2.2
.
1
</version>
</dependency>
|
使用如下:
- Implement any number of event handling methods in the subscriber:
public void onEvent(AnyEventType event) {}
- Register subscribers:
eventBus.register(this);
- Post events to the bus:
eventBus.post(event);
- Unregister subscriber:
eventBus.unregister(this);
- Implement any number of event handling methods in the subscriber:
EventBus提供了几种ThreadMode线程模型来处理事件,这个本身是可以扩展的,你完全可以按照自己的需要来自定义你所需要的线程模型:
PostThread:事件响应就在事件发布的线程,即时响应。
MainThread::事件响应在android的主线程也即UI线程,即时响应。
BackGroundThread:事件响应在后台线程。当事件发布在工作线程时,事件处理就在这个工作线程;当事件发布在主线程时,就另开一个唯一的工作线程来线性的响应事件。即时响应:
Asyn:事件响应在一个独立的工作线程,与事件发布的线程和主线程不同。一般用来来处理一些耗时的操作如网络数据等,尽量避免同时触发大量的异步线程,EventBus内部使用了一个线程池来复用线程。
而下面使用的示例,就是如果网络连接丢失,该如何通知一个活动:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
public
class
NetworkStateReceiver
extends
BroadcastReceiver {
// post event if there is no Internet connection
public
void
onReceive(Context context, Intent intent) {
super
.onReceive(context, intent);
if
(intent.getExtras()!=
null
) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().
get
(ConnectivityManager.EXTRA_NETWORK_INFO);
if
(ni!=
null
&& ni.getState()==NetworkInfo.State.CONNECTED) {
// there is Internet connection
}
else
if
(intent
.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
Boolean
.FALSE)) {
// no Internet connection, send network state changed
EventBus.getDefault().post(
new
NetworkStateChanged(
false
));
}
}
// event
public
class
NetworkStateChanged {
private
mIsInternetConnected;
public
NetworkStateChanged(boolean isInternetConnected) {
this
.mIsInternetConnected = isInternetConnected;
}
public
boolean isInternetConnected() {
return
this
.mIsInternetConnected;
}
}
public
class
HomeActivity
extends
Activity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(
this
);
// register EventBus
}
@Override
protected
void
onDestroy() {
super
.onDestroy();
EventBus.getDefault().unregister(
this
);
// unregister EventBus
}
// method that will be called when someone posts an event NetworkStateChanged
public
void
onEventMainThread(NetworkStateChanged event) {
if
(!event.isInternetConnected()) {
Toast.makeText(
this
,
"No Internet connection!"
, Toast.LENGTH_SHORT).show();
}
}
}
|