Original: Android Project Combat (13): Talking about Eventbus
Overview:
The Eventbus is a publish/Subscribe event bus optimized for Android.
The main function is to replace intent,handler,broadcast in Fragment,activity,service.
Pass messages between threads. The advantage is that the overhead is small, the code is more elegant, and the sender and receiver are decoupled.
---------------------------------------------------------------------------------------
Download:
Class Library Source: Https://github.com/greenrobot/EventBus
Jar Package: http://download.csdn.net/detail/yy1300326388/8727699
---------------------------------------------------------------------------------------
Use:
Build.gradle, if you don't need to download a class library or jar package in this way, you can import
' de.greenrobot:eventbus:2.4.0 '
First, the use of Eventbus, simply speaking is 5 steps: Create a class (specifically using the following), register, send messages, receive messages, release the registration
Look at a demo:
Implementation function: There are two activity, the first activity jumps the second activity, the second activity clicks the button to send the message, the first activity in the TextView shows the received message information
1. Write down the layout of the two activity
1<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"2xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="match_parent"3android:layout_height="match_parent"android:paddingleft="@dimen/activity_horizontal_margin"4android:paddingright="@dimen/activity_horizontal_margin"5android:paddingtop="@dimen/activity_vertical_margin"6Android:paddingbottom="@dimen/activity_vertical_margin"7android:orientation="Vertical"8tools:context=". Mainactivity">9 Ten<TextView Oneandroid:layout_gravity="Center" AAndroid:id="@+id/show_msg" -android:text="@string/hello_world" -Android:layout_width="wrap_content" theandroid:layout_height="wrap_content"/> - -<Button -Android:id="@+id/to_second_activity" +android:layout_gravity="Center" -Android:layout_width="wrap_content" +android:layout_height="wrap_content" Aandroid:text="jump to a second activity"/> at -</LinearLayout>
Activity_main
1<?xml version="1.0"encoding="Utf-8"?>2<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"3android:orientation="Vertical"Android:layout_width="match_parent"4android:layout_height="match_parent">5 6<Button7Android:layout_width="wrap_content"8android:layout_height="wrap_content"9android:text="send a message"TenAndroid:id="@+id/send_msg"/> One A<Button -Android:id="@+id/btn_finish" -android:text="destroy this activity and return to the first activity" theAndroid:layout_width="wrap_content" -android:layout_height="wrap_content"/> -</LinearLayout>
Activity_second
2, create a class, construction method parameters are not fixed, write casually, empty classes can also be used to convey messages, to see the specific needs
Package Com.xqx.com.eventbusdemo; Public class mymessage { privatestring; Public string ) { this. Stringstring; } Public string getString () { returnString; }}
3. Register and de-register eventbus on the page where you receive the message (the first activity), and obtain and process the message
Registering in the OnCreate () method
Eventbus.getdefault (). Register (this);
Unregister in the OnDestroy () method
Eventbus.getdefault (). Unregister (this);
Implements a method for getting a message processed, first using the Oneventmainthread () method, meaning to receive a message and manipulate it in the UI thread
Public void Event { "Oneventmainthread received the message:"event. getString (); Show_msg.settext (msg); }
Full code:
Package Com.xqx.com.eventbusdemo;import Android.app.activity;import android.content.intent;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.widget.button;import Android.widget.TextView;import De.greenrobot.Event. Eventbus; Public classMainactivity extends Activity {//button to open a second activity PrivateButton to_second_activity; //text that shows the received message PrivateTextView show_msg; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); To_second_activity=(Button) Findviewbyid (r.id.to_second_activity); Show_msg=(TextView) Findviewbyid (r.id.show_msg); //RegisterEventbus.getdefault (). Register ( This); //Click the button to enter the second activityTo_second_activity.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {startactivity (NewIntent (mainactivity. This, Secondactivity.class)); } }); } //receive messages and process Public voidOneventmainthread (mymessageEvent) {String msg="Oneventmainthread received a message:"+Event. getString (); Show_msg.settext (msg); } @Overrideprotected voidOnDestroy () {Super.ondestroy (); //Cancel RegistrationEventbus.getdefault (). Unregister ( This); }}Mainactivity.class
4. Send a message on the page where you want to send the message
Sending a message is simple, the argument is the class you wrote yourself
Eventbus.getdefault (). Post (new mymessage ("This isa message");
Full code:
Package Com.xqx.com.eventbusdemo;import Android.app.activity;import android.os.bundle;import Android.view.View ; import Android.widget.button;import De.greenrobot.Event. Eventbus; Public classSecondactivity extends activity{PrivateButton send_msg; PrivateButton Btn_finish; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_second); Send_msg=(Button) Findviewbyid (r.id.send_msg); Btn_finish=(Button) Findviewbyid (r.id.btn_finish); Send_msg.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {eventbus.getdefault (). Post (NewMymessage ("This is a message")); } }); Btn_finish.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {finish (); } }); }}Secondactivity.class
---------------------------------------------------------------------------------------
Eventbus Other Knowledge Description:
1, Eventbus has four different message receive processing method:
OnEvent:
With OnEvent, the event is published on which thread, and onevent runs in that thread, that is, the publishing event and the receiving event thread are on the same thread. With this approach, time-consuming operations cannot be performed in the OnEvent method, which can lead to delays in event distribution if the execution of time-consuming operations is easy.
Oneventmainthread:
With Oneventmainthread, the Oneventmainthread executes in the UI thread regardless of which thread the event was published in, and the receive event runs in the UI thread, which is very useful in Android. Because the new UI can only be followed in the UI thread in Android, it is not possible to perform time-consuming operations in the Onevnetmainthread method.
Oneventbackgroundthread:
With Oneventbackgrondthread, if the event is published in the UI thread, then Oneventbackground will run in the child thread, if the event is originally published in a child thread, Then the Oneventbackground function executes directly in the child thread.
Oneventasync:
With Oneventasync, a new child thread is created to execute Oneventasync regardless of which thread the event is published on.
2, if there are multiple places to send messages, and there are several message processing functions, how to determine which message processing method to handle which messages?
This depends on the parameters of the four message processing methods. The parameter that sends the message is a class, and it must be received by this class, otherwise it cannot be received. These methods can receive messages if there are multiple OnEvent () method parameters.
---------------------------------------------------------------------------------------
Summarize:
Register (register) will put the matching method (OnEvent) in the current class into a map, and post will go to map lookup for reflection calls based on the arguments
Android Project Combat (13): Talking about Eventbus