├── .gitignore
├── .idea
├── .gitignore
├── compiler.xml
├── gradle.xml
├── libraries
│ ├── android_support_v4.xml
│ └── lib.xml
├── misc.xml
└── vcs.xml
├── LICENSE
├── README-ch.md
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── android
│ │ └── eventbus
│ │ └── demo
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── android
│ │ │ └── eventbus
│ │ │ └── demo
│ │ │ ├── MainActivity.java
│ │ │ ├── StickyActivity.java
│ │ │ ├── bean
│ │ │ ├── StickyUser.java
│ │ │ └── User.java
│ │ │ └── fragment
│ │ │ ├── BaseFragment.java
│ │ │ ├── ConstactFragment.java
│ │ │ └── MenuFragment.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── include_sticky_activity.xml
│ │ ├── list_fragment.xml
│ │ ├── main_activity.xml
│ │ ├── menu_fragment.xml
│ │ ├── sticky_activity.xml
│ │ └── test_sticky_activity.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-anydpi-v33
│ │ └── ic_launcher.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── values-land
│ │ └── dimens.xml
│ │ ├── values-night
│ │ └── themes.xml
│ │ ├── values-v29
│ │ └── themes.xml
│ │ ├── values-w1240dp
│ │ └── dimens.xml
│ │ ├── values-w600dp
│ │ └── dimens.xml
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ └── xml
│ │ ├── backup_rules.xml
│ │ └── data_extraction_rules.xml
│ └── test
│ └── java
│ └── com
│ └── android
│ └── eventbus
│ └── demo
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── lib
├── androideventbus-1.0.5.1.jar
└── androideventbus-1.0.5.jar
├── library
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ ├── com
│ │ └── android
│ │ │ └── eventbus
│ │ │ └── library
│ │ │ └── ExampleInstrumentedTest.java
│ │ └── org
│ │ └── simple
│ │ └── eventbus
│ │ └── test
│ │ ├── DefaultMatchPolicyTest.java
│ │ ├── EventBusTest.java
│ │ ├── EventTypeTest.java
│ │ ├── PrimitiveEventTest.java
│ │ ├── SubscriberMethodHunterTest.java
│ │ ├── ThreadModeTest.java
│ │ └── mock
│ │ ├── MockSubcriber.java
│ │ ├── PrimitiveParamObject.java
│ │ ├── SingleSubscriber.java
│ │ ├── StickySubscriber.java
│ │ └── User.java
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── org
│ └── simple
│ └── eventbus
│ ├── EventBus.java
│ ├── EventType.java
│ ├── SubsciberMethodHunter.java
│ ├── Subscriber.java
│ ├── Subscription.java
│ ├── TargetMethod.java
│ ├── ThreadMode.java
│ ├── handler
│ ├── AsyncEventHandler.java
│ ├── DefaultEventHandler.java
│ ├── EventHandler.java
│ └── UIThreadEventHandler.java
│ └── matchpolicy
│ ├── DefaultMatchPolicy.java
│ ├── MatchPolicy.java
│ └── StrictMatchPolicy.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.project
2 | *.classpath
3 | bin/
4 | gen/
5 | *.DS_Store
6 | app/build/
7 | library/build/
8 |
9 | */bin/
10 | */gen/
11 | .settings/
12 | # Built application files
13 | *.apk
14 | *.ap_
15 |
16 | releases/
17 |
18 | # Files for the Dalvik VM
19 | *.dex
20 |
21 | # Java class files
22 | *.class
23 |
24 | # Generated files
25 | bin/
26 | gen/
27 |
28 | # Gradle files
29 | .gradle/
30 | build/
31 |
32 | # Local configuration file (sdk path, etc)
33 | local.properties
34 |
35 | # Proguard folder generated by Eclipse
36 | proguard/
37 |
38 | # Log Files
39 | *.log
40 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/libraries/android_support_v4.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/libraries/lib.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README-ch.md:
--------------------------------------------------------------------------------
1 | #  AndroidEventBus
2 |
3 | 这是一个Android平台的事件总线框架, 它简化了Activity、Fragment、Service等组件之间的交互,很大程度上降低了它们之间的耦合,使得我们的代码更加简洁,耦合性更低,提升我们的代码质量。
4 |
5 | 更多详情请参考[AndroidEventBus 框架发布](http://blog.csdn.net/bboyfeiyu/article/details/43450553);
6 |
7 | ****A english readme is here [README-en.md](README-en.md).****
8 |
9 | ## 最新特性
10 |
11 | 1. 支持 sticky event;
12 | 2. 使用弱引用持有订阅对象。
13 |
14 | ## 使用了AndroidEventBus的已知App
15 | * [Accupass - Events around you](https://play.google.com/store/apps/details?id=com.accuvally.android.accupass)
16 | * [考拉FM](http://www.wandoujia.com/apps/com.itings.myradio)
17 | * [羞羞](http://www.wandoujia.com/apps/com.yelong.wesex)
18 | * [大题小作](http://www.pkdati.com/)
19 | * [易泊商户](http://www.myebox.cn/)
20 | * [易方达移动OA](http://www.wandoujia.com/apps/com.efunds.trade)
21 | * [功夫泡](http://gongfupao.com)
22 | * * [魅族手机中的日历应用]()
23 |
24 | `欢迎大家给我反馈使用情况`
25 |
26 | ## 基本结构
27 | 
28 | AndroidEventBus类似于观察者模式,通过register函数将需要订阅事件的对象注册到事件总线中,然后根据@Subscriber注解来查找对象中的订阅方法,并且将这些订阅方法和订阅对象存储在map中。当用户在某个地方发布一个事件时,事件总线根据事件的参数类型和tag找到对应的订阅者对象,最后执行订阅者对象中的方法。这些订阅方法会执行在用户指定的线程模型中,比如mode=ThreadMode.ASYNC则表示该订阅方法执行在子线程中,更多细节请看下面的说明。
29 |
30 | ## 使用AndroidEventBus
31 | 你可以按照下面几个步骤来使用AndroidEventBus.
32 |
33 | * 1. 注册事件接收对象
34 |
35 | ```
36 | public class YourActivity extends Activity {
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | setContentView(R.layout.main_activity);
42 | // 注册对象
43 | EventBus.getDefault().register(this);
44 | }
45 |
46 | @Override
47 | protected void onDestroy() {
48 | // 注销
49 | EventBus.getDefault().unregister(this);
50 | super.onDestroy();
51 | }
52 | }
53 |
54 | ```
55 |
56 | * 2. 通过Subscriber注解来标识事件接收对象中的接收方法
57 |
58 | ```
59 |
60 | public class YourActivity extends Activity {
61 |
62 | // code ......
63 |
64 | // 接收方法,默认的tag,执行在UI线程
65 | @Subscriber
66 | private void updateUser(User user) {
67 | Log.e("", "### update user name = " + user.name);
68 | }
69 |
70 | // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在UI线程
71 | @Subscriber(tag = "my_tag")
72 | private void updateUserWithTag(User user) {
73 | Log.e("", "### update user with my_tag, name = " + user.name);
74 | }
75 |
76 | // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,
77 | // post函数在哪个线程执行,该函数就执行在哪个线程
78 | @Subscriber(tag = "my_tag", mode=ThreadMode.POST)
79 | private void updateUserWithMode(User user) {
80 | Log.e("", "### update user with my_tag, name = " + user.name);
81 | }
82 |
83 | // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在一个独立的线程
84 | @Subscriber(tag = "my_tag", mode = ThreadMode.ASYNC)
85 | private void updateUserAsync(User user) {
86 | Log.e("", "### update user async , name = " + user.name + ", thread name = " + Thread.currentThread().getName());
87 | }
88 | }
89 |
90 | ```
91 |
92 | User类大致如下 :
93 | ```
94 | public class User {
95 | String name ;
96 | public User(String aName) {
97 | name = aName ;
98 | }
99 | }
100 | ```
101 |
102 |
103 | 接收函数使用tag来标识可接收的事件类型,与BroadcastReceiver中指定action是一样的,这样可以精准的投递消息。mode可以指定目标函数执行在哪个线程,默认会执行在UI线程,方便用户更新UI。目标方法执行耗时操作时,可以设置mode为ASYNC,使之执行在子线程中。
104 |
105 |
106 | * 3. 在其他组件,例如Activity, Fragment,Service中发布事件
107 |
108 | ```
109 |
110 | EventBus.getDefault().post(new User("android"));
111 |
112 | // post a event with tag, the tag is like broadcast's action
113 | EventBus.getDefault().post(new User("mr.simple"), "my_tag");
114 |
115 | ```
116 |
117 | 发布事件之后,注册了该事件类型的对象就会接收到响应的事件.
118 |
119 |
120 | ## 集成
121 | ### jar文件集成
122 | 将jar文件添加到工程中的引用中即可,[AndroidEventBus.jar下载](lib/androideventbus-1.0.5.1.jar?raw=true "点击下载到本地")
123 |
124 | ### Android Studio集成
125 |
126 | * 在Module的build.gradle添加依赖
127 |
128 | ```
129 | dependencies {
130 | compile fileTree(dir: 'libs', include: ['*.jar'])
131 |
132 | // 添加依赖
133 | compile 'org.simple:androideventbus:1.0.5.1'
134 |
135 | }
136 | ```
137 |
138 |
139 | ## 与greenrobot的EventBus的不同
140 | 1. greenrobot的EventBus是一个非常流行的开源库,但是它在使用体验上并不友好,例如它的订阅函数必须以onEvent开头,并且如果需要指定该函数运行的线程则又要根据规则将函数名加上执行线程的模式名,这么说很难理解,比如我要将某个事件的接收函数执行在主线程,那么函数名必须为onEventMainThread。那如果我一个订阅者中有两个参数名相同,且都执行在主线程的接收函数呢? 这个时候似乎它就没法处理了。而且规定死了函数命名,那就不能很好的体现该函数的功能,也就是函数的自文档性。AndroidEventBus使用注解来标识接收函数,这样函数名不受限制,比如我可以把接收函数名写成updateUserInfo(Person info),这样就灵活得多了。
141 | 2. 另一个不同就是AndroidEventBus增加了一个额外的tag来标识每个接收函数可接收的事件的tag,这类似于Broadcast中的action,比如每个Broadcast对应一个或者多个action,当你发广播时你得指定这个广播的action,然后对应的广播接收器才能收到.greenrobot的EventBus只是根据函数参数类型来标识这个函数是否可以接收某个事件,这样导致只要是参数类型相同,任何的事件它都可以接收到,这样的投递原则就很局限了。比如我有两个事件,一个添加用户的事件, 一个删除用户的事件,他们的参数类型都为User,那么greenrobot的EventBus大概是这样的:
142 |
143 | ```
144 |
145 | private void onEventMainThread(User aUser) {
146 | // code
147 | }
148 | ```
149 | 如果你有两个同参数类型的接收函数,并且都要执行在主线程,那如何命名呢 ? 即使你有两个符合要求的函数吧,那么我实际上是添加用户的事件,但是由于EventBus只根据事件参数类型来判断接收函数,因此会导致两个函数都会被执行。AndroidEventBus的策略是为每个事件添加一个tag,参数类型和tag共同标识一个事件的唯一性,这样就确保了事件的精确投递。
150 |
151 | 这就是AndroidEventBus和greenrobot的EventBus的不同,当然greenrobot出于性能的考虑这么处理也可以理解,但是我们在应用中发布的事件数量是很有限的,性能差异可以忽略,但使用体验上却是很直接的。另外由于本人对greenrobot的EventBus前世今生并不是很了解,很可能上述我所说的有误,如果是那样,欢迎您指出。
152 |
153 | ### 与EventBus、otto的特性对比
154 |
155 | | 名称 | 订阅函数是否可执行在其他线程 | 特点 |
156 | |---------------------|-----------------------|---------------------------------|
157 | | [greenrobot的EventBus](https://github.com/greenrobot/EventBus) | 是 | 使用name pattern模式,效率高,但使用不方便。|
158 | | [square的otto](https://github.com/square/otto) | 否 | 使用注解,使用方便,但效率比不了EventBus。 |
159 | | [AndroidEventBus]() | 是 | 使用注解,使用方便,但效率比不上EventBus。订阅函数支持tag(类似广播接收器的Action)使得事件的投递更加准确,能适应更多使用场景。 |
160 |
161 |
162 | ## 混淆配置
163 |
164 | ```
165 | -keep class org.simple.** { *; }
166 | -keep interface org.simple.** { *; }
167 | -keepclassmembers class * {
168 | @org.simple.eventbus.Subscriber ;
169 | }
170 | -keepattributes *Annotation*
171 | ```
172 |
173 | ## 感谢
174 | 在此非常感谢网友“淡蓝色的星期三”提出的bug以及反馈,也希望更多的朋友能够加入到Android EventBus的开发中来。
175 |
176 |
177 | ## 发布历史
178 |
179 | ### V1.0.4 ( 2015.5.23 )
180 | 1. 支持Sticky事件;
181 | 2. 弱引用持有订阅对象。
182 |
183 |
184 | ### V1.0.2 ( 2015.2.28 )
185 | 1. 修复订阅方法的参数是基本类型( int, boolean等 )不能接收事件的问题。
186 |
187 | ### 1.0.1 ( 2015.2.13 )
188 | 1. 修复订阅方法是基类,而发布事件时传递的是子类型导致订阅方法无法接收到事件的问题。
189 |
190 |
191 | ### v1.0 ( 2015.2.9 )
192 | 1. 事件总线框架发布,使用@Subscriber注解标识订阅方法;
193 | 2. 订阅方法支持tag标识,使得事件投递更加精准。
194 |
195 |
196 | ## License
197 | ```
198 | Copyright (C) 2015 Mr.Simple
199 |
200 | Licensed under the Apache License, Version 2.0 (the "License");
201 | you may not use this file except in compliance with the License.
202 | You may obtain a copy of the License at
203 |
204 | http://www.apache.org/licenses/LICENSE-2.0
205 |
206 | Unless required by applicable law or agreed to in writing, software
207 | distributed under the License is distributed on an "AS IS" BASIS,
208 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
209 | See the License for the specific language governing permissions and
210 | limitations under the License.
211 | ```
212 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AndroidEventBus
2 |
3 | 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.
4 |
5 | [//]: # ( ****中文版 [README.md](README-ch.md).【该项目不再维护】**** )
6 |
7 | ## new feature
8 |
9 | 1. support sticky event;
10 |
11 | ## AndroidEventBus is adopted in the following app
12 | * [Accupass - Events around you](https://play.google.com/store/apps/details?id=com.accuvally.android.accupass)
13 | * [考拉FM](http://www.wandoujia.com/apps/com.itings.myradio)
14 | * [羞羞](http://www.wandoujia.com/apps/com.yelong.wesex)
15 | * [大题小作](http://www.pkdati.com/)
16 | * [易方达移动OA](http://www.wandoujia.com/apps/com.efunds.trade)
17 | * [Novu - Your Health Rewarded](https://play.google.com/store/apps/details?id=com.novu.novu)
18 | * [魅族手机中的日历应用]()
19 |
20 | ## Basic Architecture
21 | 
22 |
23 | 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.
24 |
25 |
26 | ## Code Example
27 | You can use AndroidEventBus according to the following steps.
28 |
29 | * 1. Event-receiving Object
30 |
31 | ```
32 |
33 | public class YourActivity extends Activity {
34 |
35 | @Override
36 | protected void onCreate(Bundle savedInstanceState) {
37 | super.onCreate(savedInstanceState);
38 | setContentView(R.layout.main_activity);
39 | // register the receiver object
40 | EventBus.getDefault().register(this);
41 | }
42 |
43 | @Override
44 | protected void onDestroy() {
45 | // Don’t forget to unregister !!
46 | EventBus.getDefault().unregister(this);
47 | super.onDestroy();
48 | }
49 | }
50 |
51 | ```
52 |
53 | * 2. Mark the receiving method of the Event-receiving Object with Subscriber annotation.
54 |
55 | ```
56 | public class YourActivity extends Activity {
57 |
58 | // code ......
59 |
60 | // A receiving method with a default tag will execute on UI thread.
61 | @Subscriber
62 | private void updateUser(User user) {
63 | Log.e("", "### update user name = " + user.name);
64 | }
65 |
66 | // When there is a “my_tag”, only events designated with “my_tag” can
67 | // trigger the function and execute on UI thread when a user posts an event.
68 | @Subscriber(tag = "my_tag")
69 | private void updateUserWithTag(User user) {
70 | Log.e("", "### update user with my_tag, name = " + user.name);
71 | }
72 |
73 | // When there is a “my_tag”, only events designated with “my_tag” can trigger the function.
74 | // The function will execute on the same thread as the one post function is executed on.
75 | @Subscriber(tag = "my_tag", mode=ThreadMode.POST)
76 | private void updateUserWithMode(User user) {
77 | Log.e("", "### update user with my_tag, name = " + user.name);
78 | }
79 |
80 | // When there is a “my_tag”, only events designated with “my_tag” can trigger
81 | // the function and execute on an independent thread when a user posts an event.
82 | @Subscriber(tag = "my_tag", mode = ThreadMode.ASYNC)
83 | private void updateUserAsync(User user) {
84 | Log.e("", "### update user async , name = " + user.name + ", thread name = " + Thread.currentThread().getName());
85 | }
86 | }
87 |
88 | ```
89 |
90 | User class is approximately as follows :
91 |
92 | ```
93 | public class User {
94 | String name ;
95 | public User(String aName) {
96 | name = aName ;
97 | }
98 | }
99 | ```
100 |
101 | 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.
102 |
103 |
104 | * 3. To post an event in other components such as Activities, Fragments or Services.
105 |
106 | ```
107 |
108 | EventBus.getDefault().post(new User("android"));
109 |
110 | // post a event with tag, the tag is like broadcast's action
111 | EventBus.getDefault().post(new User("mr.simple"), "my_tag");
112 |
113 | // post sticky event
114 | EventBus.getDefault().postSticky(new User("sticky"));
115 |
116 | ```
117 |
118 | After posting the event, the object registered with the event type will receive responsive event.
119 |
120 |
121 | ## Usage
122 | ### integrate with jar
123 | It will be enough to add the jar file into the “quote” part of the Project, AndroidEventBus.[AndroidEventBus.jar](lib/androideventbus-1.0.5.1.jar?raw=true "download")
124 |
125 |
126 | ### Gradle
127 |
128 | * Add dependency in build.gradle of the Module .
129 |
130 | ```
131 | dependencies {
132 |
133 | // add AndroidEventBus dependency
134 | compile 'org.simple:androideventbus:1.0.5.1'
135 | }
136 | ```
137 |
138 | ## Differing from the EventBus of greenrobot
139 | 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.
140 | 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:
141 |
142 | ```
143 |
144 | private void onEventMainThread(User aUser) {
145 | // code
146 | }
147 | ```
148 |
149 | 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.
150 |
151 | 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.
152 |
153 |
154 | ### Comparison Of Characteristics
155 |
156 | | library | Whether the subscription function can be executed on other thread | features |
157 | |---------------------|-----------------------|------------------|
158 | | [greenrobot's EventBus](https://github.com/greenrobot/EventBus) | yes | It adopts name pattern which is efficient but inconvenient to use. |
159 | | [square's otto](https://github.com/square/otto) | no | It is convenient to use annotation but it’s not as efficient as EventBus|
160 | | [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. |
161 |
162 | ## Proguard
163 |
164 | ```
165 | -keep class org.simple.** { *; }
166 | -keep interface org.simple.** { *; }
167 | -keepclassmembers class * {
168 | @org.simple.eventbus.Subscriber ;
169 | }
170 | -keepattributes *Annotation*
171 | ```
172 |
173 | ## Thanks Note
174 | 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.
175 |
176 |
177 | ## Release Note
178 |
179 | ### V1.0.5 ( 2015.6.20 )
180 | 1. fix bugs.
181 |
182 | ### V1.0.4 ( 2015.5.23 )
183 | 1. support Sticky Events and use WeakReference to hold the Subscriber.
184 |
185 |
186 | ### V1.0.2 ( 2015.2.28 )
187 | Solved the problem of failing to receive an event when the parameter of the subscription method is a basic type (int, Boolean, etc.)
188 |
189 | ### V1.0.1 ( 2015.2.13 )
190 | 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.
191 |
192 |
193 | ### v1.0 ( 2015.2.9 )
194 | 1. Release an EventBus library; use @Subscriber annotation to mark subscription method
195 | 2. The subscription method supports “tag” mark, which makes event delivery more precise.
196 |
197 |
198 | ## License
199 | ```
200 | Copyright (C) 2015 Mr.Simple
201 |
202 | Licensed under the Apache License, Version 2.0 (the "License");
203 | you may not use this file except in compliance with the License.
204 | You may obtain a copy of the License at
205 |
206 | http://www.apache.org/licenses/LICENSE-2.0
207 |
208 | Unless required by applicable law or agreed to in writing, software
209 | distributed under the License is distributed on an "AS IS" BASIS,
210 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
211 | See the License for the specific language governing permissions and
212 | limitations under the License.
213 | ```
214 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | namespace 'com.android.eventbus.demo'
8 | compileSdk 33
9 |
10 | defaultConfig {
11 | applicationId "com.android.eventbus.demo"
12 | minSdk 21
13 | targetSdk 33
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | kotlinOptions {
27 | jvmTarget = '1.8'
28 | }
29 | buildFeatures {
30 | viewBinding true
31 | }
32 | }
33 |
34 | dependencies {
35 |
36 | implementation 'androidx.appcompat:appcompat:1.6.1'
37 | implementation 'com.google.android.material:material:1.5.0'
38 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
39 | implementation project(":library")
40 |
41 |
42 | testImplementation 'junit:junit:4.13.2'
43 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
44 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
45 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/android/eventbus/demo/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.android.eventbus.demo
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.android.eventbus.demo", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
14 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Mr.Simple
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.eventbus.demo;
18 |
19 | import android.os.Bundle;
20 |
21 | import androidx.appcompat.app.AppCompatActivity;
22 |
23 | public class MainActivity extends AppCompatActivity {
24 | @Override
25 | protected void onCreate(Bundle savedInstanceState) {
26 | super.onCreate(savedInstanceState);
27 | setContentView(R.layout.main_activity);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/StickyActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License (MIT)
3 | *
4 | * Copyright (c) 2014-2015 Umeng, Inc
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package com.android.eventbus.demo;
26 |
27 | import android.app.Activity;
28 | import android.os.Bundle;
29 | import android.util.Log;
30 | import android.widget.TextView;
31 |
32 | import com.android.eventbus.demo.bean.User;
33 |
34 | import org.simple.eventbus.EventBus;
35 | import org.simple.eventbus.Subscriber;
36 |
37 | public class StickyActivity extends Activity {
38 |
39 | TextView nameTv;
40 | TextView ageTv;
41 |
42 | @Override
43 | protected void onCreate(Bundle savedInstanceState) {
44 | super.onCreate(savedInstanceState);
45 | setContentView(R.layout.sticky_activity);
46 |
47 | nameTv = (TextView) findViewById(R.id.name_tv);
48 | ageTv = (TextView) findViewById(R.id.age_tv);
49 |
50 | EventBus.getDefault().registerSticky(this);
51 | }
52 |
53 | @Subscriber
54 | private void onReceiveStickyEvent(User info) {
55 | nameTv.setText(info.name);
56 | ageTv.setText("age ----- 32");
57 |
58 | Log.e("", "### 找到 接到sticky消息 " + info.name);
59 | // 接受到事件之后可以手动移除Sticky事件
60 | EventBus.getDefault().removeStickyEvent(info.getClass());
61 | }
62 |
63 | @Override
64 | protected void onDestroy() {
65 | // EventBus.getDefault().unregister(this);
66 | super.onDestroy();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/bean/StickyUser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License (MIT)
3 | *
4 | * Copyright (c) 2014-2015 Umeng, Inc
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package com.android.eventbus.demo.bean;
26 |
27 | public class StickyUser extends User {
28 |
29 | public StickyUser(String aName) {
30 | super(aName + " - Sticky");
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/bean/User.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Mr.Simple
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.eventbus.demo.bean;
18 |
19 | public class User {
20 | public String name;
21 |
22 | public User(String aName) {
23 | name = aName;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return "Person [name=" + name + "]";
29 | }
30 |
31 | @Override
32 | public int hashCode() {
33 | final int prime = 31;
34 | int result = 1;
35 | result = prime * result + ((name == null) ? 0 : name.hashCode());
36 | return result;
37 | }
38 |
39 | @Override
40 | public boolean equals(Object obj) {
41 | if (this == obj)
42 | return true;
43 | if (obj == null)
44 | return false;
45 | if (getClass() != obj.getClass())
46 | return false;
47 | User other = (User) obj;
48 | if (name == null) {
49 | if (other.name != null)
50 | return false;
51 | } else if (!name.equals(other.name))
52 | return false;
53 | return true;
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/fragment/BaseFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License (MIT)
3 | *
4 | * Copyright (c) 2014-2015 Umeng, Inc
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package com.android.eventbus.demo.fragment;
26 |
27 | import android.util.Log;
28 |
29 | import androidx.fragment.app.Fragment;
30 |
31 | import com.android.eventbus.demo.bean.User;
32 |
33 | import org.simple.eventbus.Subscriber;
34 |
35 | /**
36 | * @author mrsimple
37 | */
38 | public class BaseFragment extends Fragment {
39 |
40 | static final String SUPER_TAG = "super_tag";
41 |
42 | @Subscriber(tag = SUPER_TAG)
43 | private void privateMethodInSuper(User user) {
44 | Log.e(getTag(), "### supper private Method In Super invoked ( default tag ) ");
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/fragment/ConstactFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Mr.Simple
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.eventbus.demo.fragment;
18 |
19 | import android.os.Bundle;
20 | import android.view.LayoutInflater;
21 | import android.view.View;
22 | import android.view.ViewGroup;
23 | import android.widget.AdapterView;
24 | import android.widget.AdapterView.OnItemClickListener;
25 | import android.widget.ArrayAdapter;
26 | import android.widget.BaseAdapter;
27 | import android.widget.ListView;
28 | import android.widget.Toast;
29 |
30 | import androidx.fragment.app.Fragment;
31 |
32 | import com.android.eventbus.demo.R;
33 | import com.android.eventbus.demo.bean.User;
34 |
35 | import org.simple.eventbus.EventBus;
36 | import org.simple.eventbus.Subscriber;
37 | import org.simple.eventbus.ThreadMode;
38 |
39 | import java.util.LinkedList;
40 | import java.util.List;
41 |
42 | /**
43 | * @author mrsimple
44 | */
45 | public class ConstactFragment extends Fragment {
46 |
47 | BaseAdapter mAdapter;
48 | List mConstacts = new LinkedList();
49 | ListView mListView;
50 |
51 | @Override
52 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
53 | mListView = (ListView) inflater.inflate(R.layout.list_fragment, container, false);
54 |
55 | mockDatas();
56 | initListView();
57 |
58 | EventBus.getDefault().register(this);
59 | return mListView;
60 | }
61 |
62 | private void initListView() {
63 | mAdapter = new ArrayAdapter(getActivity(),
64 | android.R.layout.simple_list_item_1, mConstacts);
65 | mListView.setAdapter(mAdapter);
66 |
67 | mListView.setOnItemClickListener(new OnItemClickListener() {
68 | @Override
69 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
70 | // 点击用户,发布消息,
71 | // tag为MenuFragment.CLICK_TAG,接收函数在MenuFragment的updateClickUserName中
72 | EventBus.getDefault().post(mConstacts.get(position), MenuFragment.CLICK_TAG);
73 | }
74 | });
75 | }
76 |
77 | @Subscriber
78 | private void primitiveParam(int aInt) {
79 | Toast.makeText(getActivity(), "int = " + aInt, Toast.LENGTH_SHORT).show();
80 | }
81 |
82 | @Subscriber
83 | private void primitiveArrayParam(int[] aInt) {
84 | Toast.makeText(getActivity(), "int array = " + aInt[0] + ", " + aInt[1], Toast.LENGTH_SHORT)
85 | .show();
86 | }
87 |
88 | @Subscriber
89 | private void primitiveParam(boolean ab) {
90 | Toast.makeText(getActivity(), "boolean = " + ab, Toast.LENGTH_SHORT).show();
91 | }
92 |
93 | @Override
94 | public void onDestroy() {
95 | EventBus.getDefault().unregister(this);
96 | super.onDestroy();
97 | }
98 |
99 | private void mockDatas() {
100 | for (int i = 0; i < 6; i++) {
101 | mConstacts.add(new User("User - " + i));
102 | }
103 | }
104 |
105 | /**
106 | * @param person
107 | */
108 | @Subscriber
109 | public void addPerson(User person) {
110 | mConstacts.add(person);
111 | mAdapter.notifyDataSetChanged();
112 | }
113 |
114 | /**
115 | * 含有tag标识的函数
116 | *
117 | * @param person
118 | */
119 | @Subscriber(tag = MenuFragment.REMOVE_TAG)
120 | private void removePersonPrivate(User person) {
121 | mConstacts.remove(person);
122 | mAdapter.notifyDataSetChanged();
123 | }
124 |
125 | /**
126 | * 执行在异步线程的函数
127 | * @param person
128 | */
129 | @Subscriber(tag = MenuFragment.ASYNC_TAG, mode = ThreadMode.ASYNC)
130 | private void asyncMethod(final User person) {
131 | try {
132 | final String threadName = Thread.currentThread().getName();
133 | mListView.post(new Runnable() {
134 |
135 | @Override
136 | public void run() {
137 | Toast.makeText(getActivity(),
138 | R.string.execute_async + threadName + ", User Info : " + person,
139 | Toast.LENGTH_LONG)
140 | .show();
141 | }
142 | });
143 | Thread.sleep(5 * 1000);
144 | } catch (InterruptedException e) {
145 | e.printStackTrace();
146 | }
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/eventbus/demo/fragment/MenuFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Mr.Simple
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.eventbus.demo.fragment;
18 |
19 | import android.content.Intent;
20 | import android.os.Bundle;
21 | import android.util.Log;
22 | import android.view.LayoutInflater;
23 | import android.view.View;
24 | import android.view.View.OnClickListener;
25 | import android.view.ViewGroup;
26 | import android.widget.TextView;
27 |
28 | import com.android.eventbus.demo.R;
29 | import com.android.eventbus.demo.StickyActivity;
30 | import com.android.eventbus.demo.bean.StickyUser;
31 | import com.android.eventbus.demo.bean.User;
32 |
33 | import org.simple.eventbus.EventBus;
34 | import org.simple.eventbus.Subscriber;
35 | import org.simple.eventbus.ThreadMode;
36 |
37 | import java.util.ArrayList;
38 | import java.util.List;
39 | import java.util.Random;
40 |
41 | /**
42 | *