[Android Development] Summary of EventBus3 Usage Course

Keywords: github network Android Gradle

First, what is EventBus?

EventBus is an Android-side optimized publish/subscribe message bus, which simplifies the communication between components in the application, between components and background threads, such as network requests, and when the network returns, it notifies the UI through Handler or Broadcast. The communication between two fragments needs to be through Listener. These requirements can be realized through EventBus.

Github address:
https://github.com/greenrobot/EventBus

II. Use Steps

2.1 Add jar packages

Add in build.gradle

compile 'org.greenrobot:eventbus:3.0.0'

2.2 registration

Register in the activity that needs to receive messages

EventBus.getDefault().register(MainActivity.this);

2.3 Unregistration

The corresponding activity is destroyed to unlock EventBus and release memory

/**
 * Unregister EventBus
 */
@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(MainActivity.this);
}

2.4 Construct Sending Information Class

Create a new class called MessageEvent for messaging. This class can be customized or you can use String. The type of sending and receiving must be consistent in order to receive it.

/**
 * EventBus Sending Information Class
 */
public class MessageEvent {

    String name;

    public MessageEvent(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.5 Release

The parameter type of this post must be the same as the type of message received.

public void sendEventBusMessage(){
    EventBus.getDefault().post(new MessageEvent("balance"));
}

2.6 Receive messages

Writing methods to receive messages in registered activity must annotate Subscribe, as threadMode will say below. There is no limit to the method name of the message received.

/**
 * 5.Receiving messages, Subscribe subscribers need to be annotated
 * @param bean Customized message class that receives based on the class identifier
 */
@Subscribe(threadMode = ThreadMode.MAIN)
public void receiverEvenetBusMess(MessageEvent bean){
    //Display received messages
    Toast.makeText(this,bean.getName()+"",Toast.LENGTH_SHORT).show();
}

3. Viscous Events

All the methods mentioned above need to register first, then post to receive events; if you use postSticky to send events, then you don't need to register first, you can post Sticky and then register to receive events.

3.1 Construct Sending Information Class

public class StickyMessageEvent {

    int age;


    public StickyMessageEvent(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

3.2 Release

public void sendStickyEventBusMessage(){
    EventBus.getDefault().postSticky(new StickyMessageEvent(20));
}

3.3 Receive messages

/**
 * Receive sticky events, sticky is true
 * @param bean Received messages
 */
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void receiverStickyMess(StickyMessageEvent bean){
    tvResult.setText(bean.getAge()+"");
    Toast.makeText(this,bean.getAge()+"",Toast.LENGTH_SHORT).show();
}

3.4 registration
3.5 Unregistration

Registration, reconciliation and registration are consistent with the above

IV. Annotation parameters

There are three parameters that annotations can add to receive messages.

4.1 threadMode

Thread mode, do you receive messages by identifying the thread on the annotations: _____________

/**
 * 5.To receive messages, you need to annotate Subscribe subscribers. The parameter type must be the same as the type at the time of sending.
 * @param bean
 */
@Subscribe(threadMode = ThreadMode.MAIN)
public void receiverEvenetBusMess(MessageEvent bean){
    //Display received messages
    Toast.makeText(this,bean.getName()+"",Toast.LENGTH_SHORT).show();
    tvResult.setText(bean.getName());
}

There are four types of messages
1. ThreadMode.MAIN
This means that this method is executed in the main thread and cannot handle time-consuming tasks. Usually it is used to update the UI, because updating the UI needs to be done in the UI thread...

  1. ThreadMode.BACKGROUND
    When an event is emitted in a UI thread, event handling actually creates a separate thread callback, and if it is emitted in a background thread, event handling is in that thread. The event handling method should be fast and avoid blocking background threads.

  2. ThreadMode.ASYNC
    No matter which thread the event is published, a new sub-thread is created to execute, and the sender does not need to wait for the event to be processed. This approach can be applied to the event handling method which takes a long time, such as network requests.

  3. ThreadMode.POSTING
    In which thread the message is published, the receiving method runs in this thread, that is to say, the publishing and receiving event threads are in the same thread. When using this method, time-consuming operations cannot be performed in onEvent method. If time-consuming operations are performed, event distribution delays are easily caused.

4.2 sticky viscosity

Whether it is sticky or not, the default value is false. For sticky events, you need to add this parameter to the annotation of the receiving method to receive the message. For example:

/**
 * Receive sticky events, sticky is true
 * @param bean Received messages
 */
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void receiverStickyMess(StickyMessageEvent bean){
    tvResult.setText(bean.getAge()+"");
    Toast.makeText(this,bean.getAge()+"",Toast.LENGTH_SHORT).show();
}

4.3 priority priority

Priority, the default value is 0, which means that you have multiple receiving methods. At this time, you can specify the order of receiving and add the parameter priority. The bigger the value, the earlier it is received, and the smaller it is received. For example:

    /**
     * 5.To receive messages, you need to annotate Subscribe subscribers. The parameter type must be the same as the type at the time of sending.
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 0)
    public void receiverEvenetBusMess(MessageEvent bean){
        //Display received messages
        //Toast.makeText(this,bean.getName()+"111",Toast.LENGTH_SHORT).show();
        tvResult.setText( tvResult.getText() + "\n" + bean.getName() + "000");

    }


    @Subscribe(threadMode = ThreadMode.MAIN,priority = 2)
    public void receiverEvenetBusMessTwo(MessageEvent bean){
        //Display received messages
        //Toast.makeText(this,bean.getName()+"222",Toast.LENGTH_SHORT).show();
        tvResult.setText( tvResult.getText() + "\n" + bean.getName() + "222");

    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 1)
    public void receiverEvenetBusMessThree(MessageEvent bean){
        //Display received messages
        //Toast.makeText(this,bean.getName()+"222",Toast.LENGTH_SHORT).show();
        tvResult.setText( tvResult.getText() + "\n" + bean.getName() + "111");
    }

The output of the above code is as follows:

Balance 222
 Balance 111
 Balance 000

V. Suggestions for Use

5.1 Definition of message type

Create an event class that encapsulates each of your parameters (or potentially conflicting parameters) into a class:

public class EventBean  {  
    public static class UserListEvent {  
        public List<User> users;  
    }
    public static class ItemListEvent {  
        public List<Item> items;  
    }    
} 

5.2 Performance optimization

According to Markus Junginger (EventBus creator), in 3.0, if you want to further improve the performance of your app, you need to add:

provided 'de.greenrobot:eventbus-annotation-processor:3.0.0'

It builds an index for registered classes at compile time, rather than at run time, and as a result, it doubles EventBus 3.0's performance, which is 3 to 6 times higher than 2.4's.

ps: This article is based on online information + self-practice summary

Posted by taya on Fri, 22 Mar 2019 21:33:52 -0700