The basic usage of EventBus (it can't be easier to understand than this)

The basic method of using EventBus is nothing simpler than this.
First of all, we use EventBus. We must first know what he does, and how we should use
EventBus
. It is convenient for us to pass messages in Android (in any two classes).
The use of EentBus :
1. In the class that receives the message, register in advance in onCreat

//这个地方先注册
EventBus.getDefault().register(this);

2. In the class that receives the message, when it is destroyed, it must cancel the registration, otherwise it will cause a memory leak

//这里销毁,如果不销毁有可能会造成内存泄漏
EventBus.getDefault().unregister(this);

3. Send a message

//首先先创建一个EventBus的Bean类
SignatureEvent signatureEvent = new SignatureEvent();
//给他赋值
signatureEvent.setEmail(signature);
//发送一个消息(注意:这个地方我发送的是粘性事件)
EventBus.getDefault().postSticky(signature);

The method of EventBus receiving messages
1. public void, the method name is arbitrary (but not arbitrary, it must be public)
2. There must be only 1 and parameters, and the type of this parameter must be javaBean. EventBus allocates and receives according to the parameter type Add an annotation to the message method (this annotation is added according to your own needs)

//添加一个注解
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
//这个方法是接受的方法(方法名是可以是任意起,没有任何要求)
public void event(SignatureEvent signatureEvent){
 //通过get方法拿到发送的消息
    String signature = signatureEvent.getEmail();
}

The first time I wrote it was not very clear, this time it has been improved, if you have any questions, please contact me

Guess you like

Origin blog.csdn.net/Qinbenjiaren/article/details/108156957