Today bring you an android across threads in the communication framework EventBus use and analysis of source code, the use of the framework is very simple, but need to pay attention to when using written comments, otherwise the people behind to see the data transfer can force a face of meng, in the development of ali’s manual is also recommended the framework for data transmission. Ali Development Manual click here
EventBus profile
EventBus is an open source framework for Android and Java that uses less, simpler code for decoupling, reduced dependencies, and faster development. The blog is based on EventBus V2.2.0, with some differences in later versions of the source code. This is explained later in the EventBus source code analysis.
EventBus characteristics
* Easier to use * cleaner code * faster, smaller (60K) * 1000000000+ applications already in use * multiple threading modes
EventBus use
Step1 define events
public class MessageEvent{
/* Additional fields if needed */
}
Copy the code
Step2 EventBus registered
Subscribe method: in version 2.2.0, the part after onEvent can be written as MainThread, BackgroundThread, Async, and nothing. Means to call the method in a different thread. See the source code of EventBus.
public void onEventMainThread(MessageEvent event){
//do something
}
Copy the code
registered
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
Copy the code
The cancellation
@Override
protected void onDestroy() {
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
super.onDestroy();
}
Copy the code
Step2 to send
EventBus.getDefault().post(new MessageEvent());
Copy the code
Add EventBus to the project
Gradle added:
implementation 'org. Greenrobot: eventbus: 2.2.1'
Copy the code
Maven add
<dependency> <groupId>org.greenrobot</groupId> <artifactId> eventBus </artifactId> <version>3.2.0</version> </dependency>Copy the code
Confusion to add
-keepattributes *Annotation*
-keepclassmembers class * {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# And if you use AsyncExecutor:
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
Copy the code
conclusion
The use of EventBus is actually faster and easier to achieve communication between threads and data transfer. However, if there is no detailed annotation in subsequent maintenance, it will be difficult to maintain and can only be searched globally. So “be sure to write a good note when using it!!”