The simple explanation and practice of the Android event bus distribution library Eventbus
Introduction, Eventbus Everyone should be unfamiliar, Eventbus is an Android-optimized publish/Subscribe event bus. The main function is to substitute intent,handler,broadcast for passing messages between Fragment,activity,service and threads. The advantage is that the cost is small and the code is more elegant. and decoupling the sender and receiver. Anyway can help us to develop quickly, this is really a good thing, in fact, the great God has made a more comprehensive analysis of the source code
- Android Eventbus Source parsing takes you in-depth understanding of Eventbus
I am here to simply talk about how to use and practice, here, to thank the Kaiyuan author, that is, "Android source design mode analysis and actual combat" author He Honghui
- Address: Https://github.com/greenrobot/EventBus
Eventbus has been updated to 3.0, and also optimized more well, recommended to use 3.0 and above, here first put on a github on the introduction map
Okay, let's take a step-by-step analysis of this picture.
I. Concept
Since it's a library, the first thing we have to do, is definitely to introduce his dependence.
‘org.greenrobot:eventbus:3.0.0‘
If it's eclipse, go to github and download the jar package to add to the Libs directory
- Jar Address: http://search.maven.org/#search%7cga%7c1%7cg%3a%22de.greenrobot%22%20and%20a%3a%22eventbus%22
Here we have to understand a concept, is the event bus management, understand the event bus management, you know the magic of this library, we have three points to summarize
- Put events in a queue for managing and distributing
- Ensure efficient communication and data between all parts of the application, event distribution
- Decoupling between modules
Of course, this may be a little general, let us analyze, about the event bus, a total of four parts
- Published by
- Subscribed by
- Event
- Bus
This also caters to our idea of the event bus, subscribers can subscribe to multiple events, publishers can also post any event, the publisher can also be a subscriber, his steps
- Subscription
- Registered
- Release
- Cancel Registration
Is there a rough outline for Eventbus now? Now we understand that this picture is much simpler, and publishers post events to the bus and distribute them.
Two. Explanation
We follow the process to
1. Registration
//注册 EventBus.getDefault().register(this);
A word on the register, of course, he can not only pass the context, but also the class and event subscription parameters
2. Cancellation of registration
@Override protectedvoidonDestroy() { super.onDestroy(); //取消注册 EventBus.getDefault().unregister(this); }
Unregister the same, the inside can also be the same as the registration passed parameters, we said in detail later
3. Release
There are two types of publications
- Direct Publishing
- Detention release
//直接发布,接收对象EventBus.getDefault().post("发布"//滞留发布EventBus.getDefault().postSticky("滞留发布");
4. Subscribe to process data
This is also one of his advantages in the version before 3.0, we are like this
//main thread event handling Public void onevent (messageevent event ) {log (event . Message); }//interactive thread event handling public void oneventmainthread (Messageevent event ) {Textfield.settext (event . Message); }//background thread handling public void oneventbackgroundthread (messageevent Event ) {Savetodisk (event . Message); }
After 3.0, we look at the official documentation
- http://greenrobot.org/files/eventbus/javadoc/3.0/
Event handling needs to be used in this way.
/ * *userevent need to define it yourself * / //In UI thread execution@Subscribe (Threadmode = threadmode.mainthread) Public void onuserevent(usereventEvent) { }//In background thread execution@Subscribe (Threadmode = threadmode.backgroundthread) Public void onuserevent(usereventEvent) { }//force execution in the background@Subscribe (Threadmode = threadmode.async) Public void onuserevent(usereventEvent) { }//By default, in the Send thread execution@Subscribe (Threadmode = threadmode.postthread) Public void onuserevent(usereventEvent) { }
We can annotate the notation above the method name, subscribe is the subscriber's consciousness, we define a threadmode, four modes
- Mainthread
- Backgroundthread
- Async
- Postthread
This is the effect, I do not know how many people understand? In general, after registering, you can, for example, send a message on my side, you can receive the
Third, practice
Let's go straight to a small example, the example is very simple, in one place to send a data message event, another place to receive, this should not be difficult, we all know to do, we create a new project--eventbus
We first registered, in the cancellation of the registration binding on OnDestroy (), not much said, here our main layout Nothing, a button click Send, a TextView to receive
Layout_main.xml
<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns:tools =" Http://schemas.android.com/tools " android:layout_width = "match_parent" android:layout_height =" match_parent " android:layout_margin =" 15DP " android:gravity = "center" android:orientation =; <button android:id = "@+id/btn_send" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:text = "send Event" /> <TextViewandroid:id="@+id/tv_content"android:layout_width="Wrap _content "android:layout_height="wrap_content "android:layout_margintop=" 20DP "android:textcolor="@color/coloraccent "android:textsize=" 20SP " /> </linearlayout>
We also need an entity class to save the data
Userevent
package com.lgl.eventbus;/** * 实体类 * Created by lgl on 2016/5/9. */publicclass UserEvent { /** * 这里你传递什么类型你就写什么类型 */ //文本 private String text; publicgetText() { return text; } publicvoidsetText(String text) { this.text = text; }}
Next, we send our custom message in the button's Click event
@Override publicvoidonClick(View v) { switch (v.getId()) { case R.id.btn_send: //发送自定义消息 eventnew UserEvent(); event.setText("我是萌哒哒的消息!"); EventBus.getDefault().post(event); break; } }
Then we receive this message in the main thread rollup
//主线程接收消息 @Subscribe(threadMode = ThreadMode.MAIN) publicvoidonUserEventevent) { //如果多个消息,可在实体类中添加type区分消息 tv_content.setText(event.getText()); }
Such a simple event subscription, receive is done, let's look at the effect
What I said here may be a little simpler, but Eventbus really is a very easy to use, but also a strong library, if careful and love the students go to GitHub to look at, also probably understand a train of thought, I as an old driver, also just a
Demo Download: http://download.csdn.net/detail/qq_26787115/9514941 My group, the Magical Journey to Android: 555974449, Welcome to come in exchange technology!
The simple explanation and practice of the Android event bus distribution library EventBus3.0