In Android, the open-source framework EventBus3.0 is used to implement communication between Fragment and the fragment open-source framework.

Source: Internet
Author: User
Tags eventbus

In Android, the open-source framework EventBus3.0 is used to implement communication between Fragment and the fragment open-source framework.
1. Overview

In the previous blog, I briefly introduced how to implement information interaction between fragment: Interaction Between Fragment and Activity in Android (two implementation methods). we will continue to introduce another EventBus method that can achieve this effect. (Compared with handler, interface callback, and bundle passing parameters, this is easy to use and cry)

EventBus is a message bus for efficient event publishing/subscription in Android. Instead of traditional Intent, Handler, Broadcast, or interface functions, data can be transmitted between Fragment, Activity, Service, and threads for communication and execution. As a message bus, there are three main elements:

(1) Event: Event

(2) Subscriber: Event Subscriber, accepting specific events

(3) Publisher: Event Publisher, used to notify Subscriber of an event

Combined with the three elements above EventBus, we can also call it an observer design pattern.

EventBus official website http://greenrobot.org/eventbus/

EventBus GitHub link https://github.com/greenrobot/EventBus

Links to previous blog posts:

Interaction between Fragment and Activity in Android (two implementation methods)

Two methods for creating Fragment in Android

2. in Demo example (1), the buttons on the left side of the sample, and the events triggered by Pan Houye and bikong are normal events of EventBus. (2) The sticky events button on the left side is published as sticky events. steps

Demo architecture:

3.1 export dependency packages

Use AndroidStudio2.2. Add the following code directly under dependencies in build. gradle:

compile 'org.greenrobot:eventbus:3.0.0'

Add dependencies after synchronization.

3.2 layout File

(1) layout file activity_main.xml in layout

<?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:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    tools:context="com.mly.panhouye.eventbustest.MainActivity">    <LinearLayout        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1"        android:orientation="vertical"        android:background="#6f6669">        <Button            android:layout_gravity="center_horizontal"            android:id="@+id/panhouye"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="ŋ" />        <Button            android:layout_gravity="center_horizontal"            android:id="@+id/bikonghai"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="̿պ" />        <Button            android:layout_gravity="center_horizontal"            android:id="@+id/postSticky"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="ճДʂ" />    </LinearLayout>    <FrameLayout        android:id="@+id/framelayout"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="2"></FrameLayout></LinearLayout>

(2) fragment layout file fragment_msg.xml on the right of layout

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/tv"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="no data"        android:textSize="50sp"        android:gravity="center_horizontal"/></LinearLayout>

(3) layout of the activity_main2.xml file in the demo interface of viscous events in layout

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main2"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.mly.panhouye.eventbustest.Main2Activity">    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:textSize="30sp"        android:gravity="center_horizontal"        android:id="@+id/tv"        android:text="no data"/></RelativeLayout>
3.3java implementation code

(1) Custom Event class

This demonstration shows the release of the simplest event. The event only publishes string data. The MessageEvent. java file is as follows:

package com.mly.panhouye.eventbustest;/** * Created by panchengjia on 2017/2/19 0019. */public class MessageEvent {    String data;    public MessageEvent(String data) {        this.data = data;    }}

(2) MsgFragment. java

The java class corresponding to fragment on the right, in addition to associating its corresponding fragment layout, you also need to add methods to modify the text in fragment, as follows:

package com.mly.panhouye.eventbustest;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;/** * Created by panchengjia on 2017/2/20 0020. */public class MsgFragment extends Fragment {    TextView tv;    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_msg,container,false);        tv = (TextView) view.findViewById(R.id.tv);        return view;    }    public void setText(String message){        tv.setText(message);    }}

(3) MainActivity. java

The layout of MainActivity. java is the main layout. The fragment on the right is attached to this layout. Therefore, you need to register EventBus in this class and register the current Activity as an event subscriber. The specific code is as follows:

Package com. mly. panhouye. eventbustest; import android. content. intent; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. view. view; import android. widget. button; import org. greenrobot. eventbus. eventBus; import org. greenrobot. eventbus. subscribe; import org. greenrobot. eventbus. threadMode; public class MainActivity extends AppCompatActivity implements View. onClickListener {Button panhouye, bikonghai, postSticky; MsgFragment msgFragment; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); panhouye = (Button) findViewById (R. id. panhouye); bikonghai = (Button) findViewById (R. id. bikonghai); postSticky = (Button) findViewById (R. id. postSticky); panhouye. setOnClickListener (this); bikonghai. setOnClickListener (this); postSticky. setOnClickListener (this); // Add the fragment to the frame layout on the right. msgFragment = new MsgFragment (); getSupportFragmentManager (). beginTransaction (). add (R. id. framelayout, msgFragment ). commit ();}/* It is recommended that you register EventBus * In onResume and register EventBus in a visible and interactive state to consume as little memory as possible */@ Override protected void onResume () {super. onResume (); EventBus. getDefault (). register (this);}/* It is recommended that you register EventBus in onPause (register the current Activity as an event subscriber) * to cancel registration early without affecting the function, use as little memory as possible */@ Override protected void onPause () {super. onPause (); EventBus. getDefault (). unregister (this);}/*** event publisher (click the event button to publish the event) * @ param v */@ Override public void onClick (View v) {switch (v. getId () {// (1) parameters passed in the event release can be used as modifications to the right fragment text // (2) the parameters passed in event publishing can also be used as the case R for distinguishing the event subscriber's execution methods. id. panhouye: EventBus. getDefault (). post (new MessageEvent ("pan Hou ye"); break; case R. id. bikonghai: EventBus. getDefault (). post (new MessageEvent ("bikong"); break; case R. id. postSticky: // publish EventBus for sticky events. getDefault (). postSticky (new MessageEvent ("Sticky event"); startActivity (new Intent (this, Main2Activity. class); break;}/*** custom Receiving Method of event subscriber * @ param event */@ Subscribe (threadMode = ThreadMode. MAIN) public void onMessageEvent (MessageEvent event) {// (1) modify the data published by the event publisher as text. // msgFragment. setText (event. data); // (2) use the data published by the event publisher as the differentiated switch (event. data) {case "pan Hou ye": msgFragment. setText ("panhouye"); break; case "bikong": msgFragment. setText ("bikonghai"); break ;}}}

(4) Main2Activity. java

Note: This layout is used as the subscriber to publish sticky events. You also need to register EventBus.

Package com. mly. panhouye. eventbustest; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. widget. textView; import org. greenrobot. eventbus. eventBus; import org. greenrobot. eventbus. subscribe; import org. greenrobot. eventbus. threadMode; public class Main2Activity extends AppCompatActivity {TextView TV; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main2); TV = (TextView) findViewById (R. id. TV) ;}@ Override protected void onResume () {super. onResume (); EventBus. getDefault (). register (this) ;}@ Override protected void onPause () {super. onPause (); EventBus. getDefault (). unregister (this) ;}@ Subscribe (threadMode = ThreadMode. MAIN, sticky = true) public void onMessageEvent (MessageEvent event) {// (1) modify the data published by the event publisher as text content TV. setText (event. data); // (2) differentiate the data published by the event publisher as the method execution // switch (event. data) {// case "Sticky event": // TV. setText ("panhouye"); // break ;//}}}

A published sticky event is automatically transmitted to a new subscriber after it is registered with its new subscriber. Sometimes, we also need to remove sticky events to prevent them from being transmitted.

MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class);// Better check that an event was actually posted beforeif(stickyEvent != null) {      // "Consume" the sticky event      EventBus.getDefault().removeStickyEvent(stickyEvent);      // Now do something with it}MessageEvent stickyEvent = EventBus.getDefault().removeStickyEvent(MessageEvent.class);// Better check that an event was actually posted beforeif(stickyEvent != null) {      // Now do something with it}
4. thread mode

EventBus provides four thread modes:

(1) postThread: the user will be called in the same thread. This is a publishing event (this is the default value ). Event transmission does not mean the minimum overhead, because it completely avoids thread switching. Therefore, this is the recommended mode to handle simple tasks. If it is known that the completion is a very short time, the main thread is not required. Event processing must return quickly in this mode to avoid blocking the publishing thread, which may be the main thread.

(2) MainThread: the user will be called in the main thread (UI thread ). If the publishing thread is the main thread, the event handler method will be called directly. Event Handlers in this mode must return quickly to avoid blocking the main thread.

(3) BackgrounThread: The subscriber will be called in the background thread. If the publishing thread is not the main thread, the event handler method will be called directly in the publishing thread. If the thread is the main thread, eventbus uses a separate background thread to call all events in order. Event Handlers using this mode should try to return quickly to avoid blocking background threads.

(4) Async: The event handler method is called in a separate thread. This is always independent of the publishing thread and the main thread. Releasing events never waits for the event handler method in this mode. Event Handlers use this mode if their execution may take some time, for example, for network access. Avoid triggering a large number of asynchronous handler methods that run for a long time at the same time to limit the number of concurrent threads. Eventbus uses a thread pool to effectively reuse threads notified by completed asynchronous event handlers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.