A brief introduction today, the use of Android Eventbus
Eventbus is a subscription in the official introduction ... A lot of what, in my Android rookie Eyes is used to replace the Android broadcast simple brute efficiency high;
In fact, the usage is quite simple. Three-step registration (officially called subscription) receive cancellation (unsubscribe). Not much to say directly on the code;
If you are using Android Studio directly in the Build.gradle add:
This foundation does not do too much to explain the online Jar class Library What a lot of
Here's how to use:
The first is to send the data
Eventbus.getdefault (). Post (event);//This event parameter can be sent anywhere in the project.
Receive:
Eventbus.getdefault (). Register (this);//register before receiving, otherwise it will not trigger
Oneventmainthread
public void Oneventmainthread (event event) {
The Receive method (which is described later in the low version fixed format used)
Event can be any type can only be one parameter recommended encapsulation a little bit more extensibility
Just take this place as a broadcast . Update UI to get data ..... All can
int type = Event.gettype ();
Switch (type) {
Case 1:
Break
Case 2:
}
Break
Case 3:
Break
}
}
public class Event {
private int type;
Private Object message;
public int GetType () {
return type;
}
public void SetType (int type) {
This.type = type;
}
Public Object GetMessage () {
return message;
}
public void Setmessage (Object message) {
this.message = message;
}
}
Here is the introduction ..... I believe that beginners can understand the other times and sometimes found that the new UI may not be a different project some of the reasons for the wording is still in the search
And then mention the EventBus3.0 usage is the same as the reception method is different, want to
Oneventmainthrea updating the UI
//在ui线程执行 public void onUserEvent(UserEvent event) { }
//在后台线程执行 public void onUserEvent(UserEvent event) { }
//强制在后台执行 public void onUserEvent(UserEvent event) { }
//默认方式, 在发送线程执行 public void onUserEvent(UserEvent event) { }
另外 :你不必再去约定OnEvent方法开头了该操作很简单,定义了一个hello方法,需要传入String参数,在其中操作UI操作,注意:我们添加了注解@Subscribe,其含义为订阅者,在其内传入了threadMode,我们定义为ThreadMode.MainThread,其含义为该方法在UI线程完成,这样你就不要担心抛出异常啦。是不是很简单?
Use of Android Eventbus