• Stars
    star
    1,611
  • Rank 29,049 (Top 0.6 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

AndroidEventBus

This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lowers the coupling among them to a great extent, thus making simplifier codes, lower coupling possible and improving code quality.

new feature

  1. support sticky event;

AndroidEventBus is adopted in the following app

Basic Architecture

arch

AndroidEventBus is like the Observer Pattern. It will have the objects which need to subscribe events registered into the EventBus through Function “register” and store such subscription methods and subscription objects in Map. When a user posts an event somewhere, the EventBus will find corresponding subscription object in accordance with the parameter type and tag of the Event and then execute the method in subscription object. These subscription methods will be executed in the Thread Mode designated by the user. For example, mode=ThreadMode. ASNYC means the subscription method is executed in the sub-thread. Please refer to the following instructions for more details.

Code Example

You can use AndroidEventBus according to the following steps.

    1. Event-receiving Object
   
public class YourActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        // register the receiver object
        EventBus.getDefault().register(this);
    }
    
   @Override
    protected void onDestroy() {
        // Don’t forget to unregister !!
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
   
    1. Mark the receiving method of the Event-receiving Object with Subscriber annotation.
public class YourActivity extends Activity {
 
    // code ......
    
    // A receiving method with a default tag will execute on UI thread.
    @Subscriber
    private void updateUser(User user) {
        Log.e("", "### update user name = " + user.name);
    }

	// When there is a “my_tag”, only events designated with “my_tag” can 
	// trigger the function and execute on UI thread when a user posts an event.
    @Subscriber(tag = "my_tag")
    private void updateUserWithTag(User user) {
        Log.e("", "### update user with my_tag, name = " + user.name);
    }
    
	// When there is a “my_tag”, only events designated with “my_tag” can trigger the function.
	// The function will execute on the same thread as the one post function is executed on.   
    @Subscriber(tag = "my_tag", mode=ThreadMode.POST)
    private void updateUserWithMode(User user) {
        Log.e("", "### update user with my_tag, name = " + user.name);
    }

	// When there is a “my_tag”, only events designated with “my_tag” can trigger  
	// the function and execute on an independent thread when a user posts an event.
    @Subscriber(tag = "my_tag", mode = ThreadMode.ASYNC)
    private void updateUserAsync(User user) {
        Log.e("", "### update user async , name = " + user.name + ", thread name = " + Thread.currentThread().getName());
    }
}

User class is approximately as follows :

    public class User  {
        String name ;
        public User(String aName) {
            name = aName ;
        }
    }

The receiving function will use “tag” to mark receivable types of events, just like designating “action” in BroadcastReceiver, which can deliver messages precisely. Mode can designate which thread the object function will be executed on but defaultly it will be executed on UI thread for the purpose of convenient UI update for users. When the object method executes long-running operations, the “mode” can be set as ASYNC so as to be executed on sub-thread.

    1. To post an event in other components such as Activities, Fragments or Services.
    
    EventBus.getDefault().post(new User("android"));
    
    // post a event with tag, the tag is like broadcast's action
    EventBus.getDefault().post(new User("mr.simple"), "my_tag");
    
    // post sticky event
    EventBus.getDefault().postSticky(new User("sticky"));

After posting the event, the object registered with the event type will receive responsive event.

Usage

integrate with jar

It will be enough to add the jar file into the “quote” part of the Project, AndroidEventBus.AndroidEventBus.jar

Gradle

  • Add dependency in build.gradle of the Module .
dependencies {

    // add AndroidEventBus dependency
    compile 'org.simple:androideventbus:1.0.5.1'
}

Differing from the EventBus of greenrobot

  1. EventBus of greenrobot is a popular open source library but its user experience is not as friendly. For example, its subscription function is required to start with onEvent, and if a function’s execution thread needs to be designated, it is necessary to add the mode name of execution thread in the name of the function according to certain rules. This may be difficult to understand. Let’s say, if I want the receiving function of some event to be executed on the main thread, I am required to name it as onEventMainThread. What if two of my subscribers share the same parameter name and both are executed on the receiving function of the main thread? It seems impossible to deal with it in such case. And a set-in-stone function name can’t properly reflect the function of the Function, i.e., the self-documentation of the function. AndroidEventBus uses annotation to mark receiving function, by which the function name is not limited. For example, I can name the receiving function as updateUserInfo(Person info). It’s more flexible.
  2. Another difference lies in that AndroidEventBus adds an extra tag to mark the tag of receivable event of every receiving function, just like the action in Broadcast. For instance, one Broadcast corresponds to one or more actions, and you need to designate the action of a broadcast before you can publish one and the broadcast receiver can receive. EventBus of greenrobot marks whether a function can receive a certain event only by the parameter type of the function. In this way, the function can receive all the events of the same parameter type, resulting in a limited delivery principle. Let’s say, if there are two events: one is about adding user and the other is about deleting user. Their parameter types are both User. Then the EventBus of greenrobot would be lke:

private void onEventMainThread(User aUser) {
	// code 
}

If there are two receiving functions of the same parameter type and both are executed on the main thread, how to name them distinctively? Supposing that there are two functions meeting the requirements and the event is adding user, but because the EventBus judges receiving function only by parameter type of the event, both function will be executed. The strategy of AndroidEventBus is to add a “tag” for each event, and use parameter type and “tag” to jointly mark the uniqueness of the vent so as to ensure precise delivery.

These are the differences between AndroidEventBus and EventBus of greenrobot. But it is understandable for greenrobot’s approach considering performance. And what I try to express is that there are very limited quantity of events posted in an App and the performance difference is negligible while user experience is well sensible. What I need to point out is that I know little about the ins and outs of EventsBus of greenrobot and there could be errors among what I’ve mentioned. If that happens, you are more than welcome to correct me.

Comparison Of Characteristics

library Whether the subscription function can be executed on other thread features
greenrobot's EventBus yes It adopts name pattern which is efficient but inconvenient to use.
square's otto no It is convenient to use annotation but it’s not as efficient as EventBus
AndroidEventBus yes It is convenient to use annotation but it’s not as efficient as EventBus. The subscription supports tag (like the Action in Broadcast Receiver) which can make event delivery more accurate and applicable to more usage scenarios.

Proguard

-keep class org.simple.** { *; }
-keep interface org.simple.** { *; }
-keepclassmembers class * {
    @org.simple.eventbus.Subscriber <methods>;
}
-keepattributes *Annotation*

Thanks Note

I really appreciate E-pal “淡蓝色的星期三” for his proposing of bugs and feedback and I hope more and more friends will join our team of AndroidEventBus Development.

Release Note

V1.0.5 ( 2015.6.20 )

  1. fix bugs.

V1.0.4 ( 2015.5.23 )

  1. support Sticky Events and use WeakReference to hold the Subscriber.

V1.0.2 ( 2015.2.28 )

Solved the problem of failing to receive an event when the parameter of the subscription method is a basic type (int, Boolean, etc.)

V1.0.1 ( 2015.2.13 )

  1. Solved the problem that the subscription method can’t receive an event because the subscription method is delivered as sub-type when posting an event while it was originally of basic type.

v1.0 ( 2015.2.9 )

  1. Release an EventBus library; use @Subscriber annotation to mark subscription method
  2. The subscription method supports “tag” mark, which makes event delivery more precise.

License

Copyright (C) 2015 Mr.Simple <[email protected]>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

awesome-english-ebooks

经济学人(含音频)、纽约客、卫报、连线、大西洋月刊等英语杂志免费下载,支持epub、mobi、pdf格式, 每周更新
CSS
20,476
star
2

android-tech-frontier

【停止维护】一个定期翻译国外Android优质的技术、开源库、软件架构设计、测试等文章的开源项目
10,443
star
3

the-economist-ebooks

经济学人(含音频)、纽约客、自然、新科学人、卫报、科学美国人、连线、大西洋月刊、国家地理等英语杂志免费下载、订阅(kindle推送),支持epub、mobi、pdf格式, 每周更新. The Economist 、The New Yorker 、Nature、The Atlantic 、New Scientist、The Guardian、Scientific American、Wired magazines, free download and subscription for kindle, mobi、epub、pdf format.
CSS
8,890
star
4

Colorful

基于Theme的Android动态换肤库,无需重启Activity、无需自定义View,方便的实现日间、夜间模式。
Java
1,398
star
5

iOS-tech-frontier

一个定期翻译国外iOS优质的技术、开源库、软件架构设计、测试等文章的开源项目
1,202
star
6

mockito-doc-zh

Mockito框架中文文档
1,113
star
7

android_my_pull_refresh_view

android下拉刷新实现原理【阐述基本原理,不建议使用】
Java
275
star
8

mmat

An automatically testing and analysis hprof library for android app (自动分析Android内存泄漏)
Java
178
star
9

simple_net_framework

SimpleNet网络框架,仅供学习参考,不推荐使用,不进行维护。
Java
139
star
10

android_dp_analysis_code

《Android 源码设计模式解析与实战》示例代码
Java
130
star
11

the-tech-frontier-app

The Android App for Tech Frontier
Java
121
star
12

simple_imageloader

A Simple ImageLoader for Android 【不建议使用到项目中,仅作示例】
Java
120
star
13

commonadapter

通用的ListView、RecyclerView的Adapter
Java
107
star
14

app-test-arch

Android 单元测试、Monkey、LeakCanary测试demo项目【粗略示例】
Java
98
star
15

android_jtm_sourcecode

Java
85
star
16

SimpleTvIME

简单的Android Tv远程遥控器 & 输入法 【不进行维护】
Java
79
star
17

dp-issues

Android源码设计模式解析与实战勘误
70
star
18

Chris-Android-PullToRefresh

在Chris Banes的Android-PullToRefresh的基础上增加了RecyclerView的支持与Demo
Java
56
star
19

ripplelayout

RippleLayout library
Java
50
star
20

the-hot-tech-blogs

每周六会从掘金抓取7天内最热门Android、iOS、后端、前端各20篇技术文章, 然后制作成 mobi、epub 格式的电子书推送给订阅者, 支持推送到kindle 设备、kindle手机app、普通邮箱.
42
star
21

SegmentView

This is a Android Segment Control ( View ) like iOS, support 2.3 and above.
Java
39
star
22

materiallayout

materiallayout library and demo.
Java
34
star
23

listview_nested_gridview

ListView嵌套GridView的消息流页面,解决了GridView高度和宽度问题
Java
32
star
24

jtm-techfrontier-app

Java
31
star
25

CrashCanary

Crash Log Viewer
Java
30
star
26

leakcanary-for-eclipse

用于eclipse的leakcanary
Java
30
star
27

AndroidShakeLib

Android 摇一摇手机功能
Java
23
star
28

android-jtm-issues

《Android开发进阶-从小工到专家》勘误
23
star
29

InjectDagger

Java
22
star
30

ErasableTextView

仿支付宝刮奖效果,自定义view
Java
20
star
31

umeng-social-custom-shareui

custom ui
Java
19
star
32

AndroidMvpBase

Android MVP Base Library
Java
18
star
33

simpledb

A Lightweight android database library
Java
12
star
34

AndroidImageBrowser

Android Image Browser
Java
12
star
35

tech-frontier-mvp

8
star
36

common_adapter_viewholder

common_adapter_viewholder
Java
7
star
37

FastScrollLayout

Android fast scroll layout from ListView
Java
6
star
38

te_audios

The Economist audio
5
star
39

Java-23-Design-Patterns

23 design patterns
Java
5
star
40

MockServer

mock server with Go
Go
4
star
41

mdict-analysis

Python
4
star
42

SimpleTask

A Simple Task Library to use AsyncTask easier.
Java
4
star
43

en_dict

3
star
44

bboyfeiyu.github.io

Blog repository
HTML
3
star
45

hehonghui.github.io

HTML
3
star
46

images_gridview_gallery

扫描本地图片,多图选择,异步加载,图片错位示例
Java
3
star
47

LoveWeRead

Java
3
star
48

zapr-sdk-sample-app

Java
2
star
49

SimpleNote

Java
2
star
50

fribidi

C
1
star
51

MusicPlayer2

MusicPlayer
C++
1
star
52

VolleyModule

使用Volley时封装的简单工具类
Java
1
star
53

GradleDemo

Java
1
star
54

dev-tech-frontier

开发技术前线
1
star
55

AndroidEventBus_maven

1
star