EventBus is an android-optimized publish/subscribe EventBus. It can replace broadcast, startActivityForResult, Handler, asynchronous callback, etc., to achieve communication between components and between components and background threads. It has the advantages of low overhead, more elegant code, and decoupling of sender and receiver.

Eventbus.getdefault ().register(this) subscribe to eventbus.getDefault (). Eventbus.getdefault ().post(Object Event) is called directly in the logic that needs to initiate communication to publish the event. However, if a project uses EventBus to communicate in many places, such as updating the login status of various pages after re-logging in, or receiving notification for updating messages, the code duplication rate will be very high. Moreover, if EventBus is upgraded or replaced later, each place will need to be changed. That’s a little tricky. So I usually will publish and subscribe EventBus encapsulated into BaseActivity/BaseFragment.

Next we begin the path of encapsulation:

1. Add dependencies

Add an EventBus dependency to Gradle:

compile 'org. Greenrobot: eventbus: 3.0.0'
Copy the code

2. Consider binding in base classes

2.1. We should think of it this way if we define an abstract method in BaseActivity or BaseFragment:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(isRegisterEventBus()) { EventBusUtil.register(this); }} /** * Whether to register event distribution ** @return trueBind EventBus event distribution. Default does not bind. If subclasses need to bind, copying this method returns true. */ protected BooleanisRegisterEventBus() {
    return false;
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(isRegisterEventBus()) { EventBusUtil.unregister(this); }}Copy the code

All subclasses of the Base class need to implement the isRegisterEventBus method to return whether or not to bind EventBus, which would be cumbersome for classes that do not bind EventBus.

2.2. Use annotations

Now, wouldn’t it be easier to use annotations?

Start by creating an annotation

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindEventBus {
}
Copy the code

Now, any class that is decorated with this annotation is bound to EventBus. So in the Base class:

@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // BindEventBus if BindEventBus is usedif(this.getClass().isAnnotationPresent(BindEventBus.class)){
        EventBusUtils.register(this);
    }
}

@Override
protected void onDestroy() { super.onDestroy(); // If BindEventBus is used, unbind EventBusif(this.getClass().isAnnotationPresent(BindEventBus.class)){ EventBusUtils.unregister(this); }}Copy the code

It’s much more convenient.

3. Encapsulation of events

public class Event<T> {
    private int code;
    private T data;


    public Event(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) { this.data = data; }}Copy the code

Event is passed a generic T, where T is the concrete Event class and Event encapsulates the concrete Event with the corresponding business code.

Let’s look at code again

public class EventCode {

    public static final int A = 0x111111;
    public static final int B = 0x222222;
    public static final int C = 0x333333;
    public static final int D = 0x444444;

}
Copy the code

Here you can define some business-specific codes, such as login, payment, and so on. In order to classify them in the future.

4. Processing classes

Public class EventBusUtils {/** * bind subscriber * @param subscriber */ public static void register(Object subscriber) { EventBus.getDefault().register(subscriber); } /** * @param subscriber */ public static void unregister(Object subscriber){ EventBus.getDefault().unregister(subscriber); } @param event */ public static void sendEvent(event event){eventbus.getDefault ().post(event); } /** ** send sticky events ** Sticky events, before the registration of the event, wait until the registration of the last sent sticky events will be received (must match) * Note: only the last sent sticky events will be received, the previous will not be accepted. * @param event */ public static void sendStickyEvent(Event event){ EventBus.getDefault().postSticky(event); }}Copy the code

The first two methods, which register and unregister, are already used in the Base class.

SendEvent and sendStickyEvent are specific ways to send messages, notice that Event is sent here.

5, use

5.1. In the Activity or Fragment

@BindEventBus
public class ABCActivity extends BaseActivity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(Event<ABC> event){
        // do something
    }
}
Copy the code

Inherit the Base class, using the BindEventBus annotation;

Create methods to receive and handle events.

5.2. Send a message

Event<ABC> event=new Event<>(0,new ABC());
EventBusUtils.sendEvent(event);
Copy the code

That’s ok. Let me know if you have any good suggestions.

More exciting content, pay attention to my wechat public number – Android motor vehicle.