diff --git a/.gitignore b/.gitignore
index 6d3aa94..930f450 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,9 @@
bin/
gen/
*.DS_Store
+app/build/
+library/build/
+
*/bin/
*/gen/
.settings/
@@ -10,6 +13,8 @@ gen/
*.apk
*.ap_
+releases/
+
# Files for the Dalvik VM
*.dex
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..26d3352
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..fb7f4a8
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 0000000..0081406
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/android_support_v4.xml b/.idea/libraries/android_support_v4.xml
new file mode 100644
index 0000000..00acd90
--- /dev/null
+++ b/.idea/libraries/android_support_v4.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/lib.xml b/.idea/libraries/lib.xml
new file mode 100644
index 0000000..69f6a36
--- /dev/null
+++ b/.idea/libraries/lib.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..2483849
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
deleted file mode 100644
index 7775d66..0000000
--- a/AndroidManifest.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
diff --git a/README-ch.md b/README-ch.md
new file mode 100644
index 0000000..4ea344f
--- /dev/null
+++ b/README-ch.md
@@ -0,0 +1,211 @@
+#  AndroidEventBus
+
+ 这是一个Android平台的事件总线框架, 它简化了Activity、Fragment、Service等组件之间的交互,很大程度上降低了它们之间的耦合,使得我们的代码更加简洁,耦合性更低,提升我们的代码质量。
+
+ 更多详情请参考[AndroidEventBus 框架发布](http://blog.csdn.net/bboyfeiyu/article/details/43450553);
+
+ ****A english readme is here [README-en.md](README-en.md).****
+
+## 最新特性
+
+1. 支持 sticky event;
+2. 使用弱引用持有订阅对象。
+
+## 使用了AndroidEventBus的已知App
+* [Accupass - Events around you](https://play.google.com/store/apps/details?id=com.accuvally.android.accupass)
+* [考拉FM](http://www.wandoujia.com/apps/com.itings.myradio)
+* [羞羞](http://www.wandoujia.com/apps/com.yelong.wesex)
+* [大题小作](http://www.pkdati.com/)
+* [易泊商户](http://www.myebox.cn/)
+* [易方达移动OA](http://www.wandoujia.com/apps/com.efunds.trade)
+* [功夫泡](http://gongfupao.com)
+* * [魅族手机中的日历应用]()
+
+`欢迎大家给我反馈使用情况`
+
+## 基本结构
+ 
+ AndroidEventBus类似于观察者模式,通过register函数将需要订阅事件的对象注册到事件总线中,然后根据@Subscriber注解来查找对象中的订阅方法,并且将这些订阅方法和订阅对象存储在map中。当用户在某个地方发布一个事件时,事件总线根据事件的参数类型和tag找到对应的订阅者对象,最后执行订阅者对象中的方法。这些订阅方法会执行在用户指定的线程模型中,比如mode=ThreadMode.ASYNC则表示该订阅方法执行在子线程中,更多细节请看下面的说明。
+
+## 使用AndroidEventBus
+ 你可以按照下面几个步骤来使用AndroidEventBus.
+
+* 1. 注册事件接收对象
+
+```
+public class YourActivity extends Activity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main_activity);
+ // 注册对象
+ EventBus.getDefault().register(this);
+ }
+
+ @Override
+ protected void onDestroy() {
+ // 注销
+ EventBus.getDefault().unregister(this);
+ super.onDestroy();
+ }
+}
+
+```
+
+* 2. 通过Subscriber注解来标识事件接收对象中的接收方法
+
+```
+
+public class YourActivity extends Activity {
+
+ // code ......
+
+ // 接收方法,默认的tag,执行在UI线程
+ @Subscriber
+ private void updateUser(User user) {
+ Log.e("", "### update user name = " + user.name);
+ }
+
+ // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在UI线程
+ @Subscriber(tag = "my_tag")
+ private void updateUserWithTag(User user) {
+ Log.e("", "### update user with my_tag, name = " + user.name);
+ }
+
+ // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,
+ // post函数在哪个线程执行,该函数就执行在哪个线程
+ @Subscriber(tag = "my_tag", mode=ThreadMode.POST)
+ private void updateUserWithMode(User user) {
+ Log.e("", "### update user with my_tag, name = " + user.name);
+ }
+
+ // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在一个独立的线程
+ @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类大致如下 :
+```
+ public class User {
+ String name ;
+ public User(String aName) {
+ name = aName ;
+ }
+ }
+```
+
+
+ 接收函数使用tag来标识可接收的事件类型,与BroadcastReceiver中指定action是一样的,这样可以精准的投递消息。mode可以指定目标函数执行在哪个线程,默认会执行在UI线程,方便用户更新UI。目标方法执行耗时操作时,可以设置mode为ASYNC,使之执行在子线程中。
+
+
+* 3. 在其他组件,例如Activity, Fragment,Service中发布事件
+
+```
+
+ 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");
+
+```
+
+ 发布事件之后,注册了该事件类型的对象就会接收到响应的事件.
+
+
+## 集成
+### jar文件集成
+将jar文件添加到工程中的引用中即可,[AndroidEventBus.jar下载](lib/androideventbus-1.0.5.1.jar?raw=true "点击下载到本地")
+
+### Android Studio集成
+
+* 在Module的build.gradle添加依赖
+
+```
+dependencies {
+ compile fileTree(dir: 'libs', include: ['*.jar'])
+
+ // 添加依赖
+ compile 'org.simple:androideventbus:1.0.5.1'
+
+}
+```
+
+
+## 与greenrobot的EventBus的不同
+ 1. greenrobot的EventBus是一个非常流行的开源库,但是它在使用体验上并不友好,例如它的订阅函数必须以onEvent开头,并且如果需要指定该函数运行的线程则又要根据规则将函数名加上执行线程的模式名,这么说很难理解,比如我要将某个事件的接收函数执行在主线程,那么函数名必须为onEventMainThread。那如果我一个订阅者中有两个参数名相同,且都执行在主线程的接收函数呢? 这个时候似乎它就没法处理了。而且规定死了函数命名,那就不能很好的体现该函数的功能,也就是函数的自文档性。AndroidEventBus使用注解来标识接收函数,这样函数名不受限制,比如我可以把接收函数名写成updateUserInfo(Person info),这样就灵活得多了。
+ 2. 另一个不同就是AndroidEventBus增加了一个额外的tag来标识每个接收函数可接收的事件的tag,这类似于Broadcast中的action,比如每个Broadcast对应一个或者多个action,当你发广播时你得指定这个广播的action,然后对应的广播接收器才能收到.greenrobot的EventBus只是根据函数参数类型来标识这个函数是否可以接收某个事件,这样导致只要是参数类型相同,任何的事件它都可以接收到,这样的投递原则就很局限了。比如我有两个事件,一个添加用户的事件, 一个删除用户的事件,他们的参数类型都为User,那么greenrobot的EventBus大概是这样的:
+
+```
+
+private void onEventMainThread(User aUser) {
+ // code
+}
+```
+ 如果你有两个同参数类型的接收函数,并且都要执行在主线程,那如何命名呢 ? 即使你有两个符合要求的函数吧,那么我实际上是添加用户的事件,但是由于EventBus只根据事件参数类型来判断接收函数,因此会导致两个函数都会被执行。AndroidEventBus的策略是为每个事件添加一个tag,参数类型和tag共同标识一个事件的唯一性,这样就确保了事件的精确投递。
+
+ 这就是AndroidEventBus和greenrobot的EventBus的不同,当然greenrobot出于性能的考虑这么处理也可以理解,但是我们在应用中发布的事件数量是很有限的,性能差异可以忽略,但使用体验上却是很直接的。另外由于本人对greenrobot的EventBus前世今生并不是很了解,很可能上述我所说的有误,如果是那样,欢迎您指出。
+
+### 与EventBus、otto的特性对比
+
+| 名称 | 订阅函数是否可执行在其他线程 | 特点 |
+|---------------------|-----------------------|---------------------------------|
+| [greenrobot的EventBus](https://github.com/greenrobot/EventBus) | 是 | 使用name pattern模式,效率高,但使用不方便。|
+| [square的otto](https://github.com/square/otto) | 否 | 使用注解,使用方便,但效率比不了EventBus。 |
+| [AndroidEventBus]() | 是 | 使用注解,使用方便,但效率比不上EventBus。订阅函数支持tag(类似广播接收器的Action)使得事件的投递更加准确,能适应更多使用场景。 |
+
+
+## 混淆配置
+
+```
+-keep class org.simple.** { *; }
+-keep interface org.simple.** { *; }
+-keepclassmembers class * {
+ @org.simple.eventbus.Subscriber ;
+}
+-keepattributes *Annotation*
+```
+
+## 感谢
+ 在此非常感谢网友“淡蓝色的星期三”提出的bug以及反馈,也希望更多的朋友能够加入到Android EventBus的开发中来。
+
+
+## 发布历史
+
+### V1.0.4 ( 2015.5.23 )
+1. 支持Sticky事件;
+2. 弱引用持有订阅对象。
+
+
+### V1.0.2 ( 2015.2.28 )
+1. 修复订阅方法的参数是基本类型( int, boolean等 )不能接收事件的问题。
+
+### 1.0.1 ( 2015.2.13 )
+1. 修复订阅方法是基类,而发布事件时传递的是子类型导致订阅方法无法接收到事件的问题。
+
+
+### v1.0 ( 2015.2.9 )
+1. 事件总线框架发布,使用@Subscriber注解标识订阅方法;
+2. 订阅方法支持tag标识,使得事件投递更加精准。
+
+
+## License
+```
+Copyright (C) 2015 Mr.Simple
+
+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.
+```
diff --git a/README-en.md b/README-en.md
deleted file mode 100644
index 5a4f5a6..0000000
--- a/README-en.md
+++ /dev/null
@@ -1,79 +0,0 @@
-#  AndroidEventBus
- A eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.
-
-## Architecture Overview
-
-
-
-
-## Usage
- It's easy to use AndroidEventBus, here is the steps.
-1. register the subcriber object
-```java
-
-public class YourActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main_activity);
- // register this as a subscrober
- EventBus.getDefault().register(this);
- }
- @Override
- protected void onDestroy() {
- // don't forget to unregister
- EventBus.getDefault().unregister(this);
- super.onDestroy();
- }
-}
-
-```
-
-3. use Subscriber annotation to mark a receiver method
-```java
-public class YourActivity extends Activity {
- // code ......
-
- @Subcriber
- private void updateTime(String time) {
- Log.e("", "### update time = " + time);
- }
-
- @Subcriber(tag = "my_tag")
- private void updateTimeWithTag(String time) {
- Log.e("", "### update time with my_tag, time = " + time);
- }
-
- @Subcriber(tag = "my_tag", mode = ThreadMode.ASYNC)
- private void updateTimeAsync(String time) {
- Log.e("", "### update time async , time = " + time + ", thread name = " + Thread.currentThread().getName());
- }
-}
-```
- when you set tag field , the method will only receive the event with a corresponding tag.
-
-4. in other activity, service, fragment , etc. you can post a event to subcribers.
-```java
- EventBus.getDefault().post("what's the time now ?");
- // post a event with tag, the tag is like broadcast's action
- EventBus.getDefault().post(new Date().toLocaleString(), "my_tag");
-```
-
-
-## License
-```
-Copyright (C) 2015 Mr.Simple
-
-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.
-```
diff --git a/README.md b/README.md
index 1654020..f6ffb07 100644
--- a/README.md
+++ b/README.md
@@ -1,38 +1,34 @@
-#  AndroidEventBus
+# AndroidEventBus
- 这是一个Android平台的事件总线框架, 它简化了Activity、Fragment、Service等组件之间的交互,很大程度上降低了它们之间的耦合,使得我们的代码更加简洁,耦合性更低,提升我们的代码质量。
+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.
+
+[//]: # ( ****中文版 [README.md](README-ch.md).【该项目不再维护】**** )
+
+## new feature
- 在往下看之前,你可以考虑这么一个场景,两个Fragment之间的通信你会怎么实现?
- 按照Android官方给的建议的解决方法如下: [Communicating with the Activity](http://developer.android.com/intl/zh-cn/guide/components/fragments.html#CommunicatingWithActivity),思路就是Activity实现某个接口,然后在Fragment-A关联上Activity之后将Activity强转为接口类型,然后在某个时刻Fragment中回调这个接口,然后再从Activity中调用Fragment-B中方法。这个过程是不是有点复杂呢? 如果你也这么觉得,那也就是你继续看下去的理由了。
-
- ****A english readme is here [README-en.md](README-en.md).****
+1. support sticky event;
+
+## AndroidEventBus is adopted in the following app
+* [Accupass - Events around you](https://play.google.com/store/apps/details?id=com.accuvally.android.accupass)
+* [考拉FM](http://www.wandoujia.com/apps/com.itings.myradio)
+* [羞羞](http://www.wandoujia.com/apps/com.yelong.wesex)
+* [大题小作](http://www.pkdati.com/)
+* [易方达移动OA](http://www.wandoujia.com/apps/com.efunds.trade)
+* [Novu - Your Health Rewarded](https://play.google.com/store/apps/details?id=com.novu.novu)
+* [魅族手机中的日历应用]()
-## 基本结构
- 
- AndroidEventBus类似于观察者模式,通过register函数将需要订阅事件的对象注册到事件总线中,然后根据@Subcriber注解来查找对象中的订阅方法,并且将这些订阅方法和订阅对象存储在map中。当用户在某个地方发布一个事件时,事件总线根据事件的参数类型和tag找到对应的订阅者对象,最后执行订阅者对象中的方法。这些订阅方法会执行在用户指定的线程模型中,比如mode=ThreadMode.ASYNC则表示该订阅方法执行在子线程中,更多细节请看下面的说明。
-
-## 与greenrobot的EventBus的不同
- 1. greenrobot的EventBus是一个非常流行的开源库,但是它在使用体验上并不友好,例如它的订阅函数必须以onEvent开头,并且如果需要指定该函数运行的线程则又要根据规则将函数名加上执行线程的模式名,这么说很难理解,比如我要将某个事件的接收函数执行在主线程,那么函数名必须为onEventMainThread。那如果我一个订阅者中有两个参数名相同,且都执行在主线程的接收函数呢? 这个时候似乎它就没法处理了。而且规定死了函数命名,那就不能很好的体现该函数的功能,也就是函数的自文档性。AndroidEventBus使用注解来标识接收函数,这样函数名不受限制,比如我可以把接收函数名写成updateUserInfo(Person info),这样就灵活得多了。
- 2. 另一个不同就是AndroidEventBus增加了一个额外的tag来标识每个接收函数可接收的事件的tag,这类似于Broadcast中的action,比如每个Broadcast对应一个或者多个action,当你发广播时你得指定这个广播的action,然后对应的广播接收器才能收到.greenrobot的EventBus只是根据函数参数类型来标识这个函数是否可以接收某个事件,这样导致只要是参数类型相同,任何的事件它都可以接收到,这样的投递原则就很局限了。比如我有两个事件,一个添加用户的事件, 一个删除用户的事件,他们的参数类型都为User,那么greenrobot的EventBus大概是这样的:
-
-```java
+## Basic Architecture
+ 
+
+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.
-private void onEventMainThread(User aUser) {
- // code
-}
-```
- 如果你有两个同参数类型的接收函数,并且都要执行在主线程,那如何命名呢 ? 即使你有两个符合要求的函数吧,那么我实际上是添加用户的事件,但是由于EventBus只根据事件参数类型来判断接收函数,因此会导致两个函数都会被执行。AndroidEventBus的策略是为每个事件添加一个tag,参数类型和tag共同标识一个事件的唯一性,这样就确保了事件的精确投递。
- 这就是AndroidEventBus和greenrobot的EventBus的不同,但是由于本人对greenrobot的EventBus并不是很了解,很可能上述我所说的有误,如果是那样,欢迎您指出。
-
- AndroidEventBus起初只是为了学习,但是在学习了EventBus的实现之后,发现它在使用上有些不便之处,我想既然我有这些感觉,应该也是有同感之人,在开发群里交流之后,发现确实有这样的情况。因此才将正式地AndroidEventBus以开源库的形式推出来,希望能够帮助到一些需要的人。当然,这个库的成长需要大家的支持与测试,欢迎大家发 pull request。如果你需要的是一个相对稳定的库,greenrobot的EventBus和square的otto都是非常好的选择。
-
-## 使用AndroidEventBus
- 你可以按照下面几个步骤来使用AndroidEventBus.
+## Code Example
+ You can use AndroidEventBus according to the following steps.
-* 1. 注册事件接收对象
+* 1. Event-receiving Object
-```java
+```
public class YourActivity extends Activity {
@@ -40,13 +36,13 @@ public class YourActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
- // 注册对象
+ // register the receiver object
EventBus.getDefault().register(this);
}
- @Override
+ @Override
protected void onDestroy() {
- // 不要忘记注销!!!!
+ // Don’t forget to unregister !!
EventBus.getDefault().unregister(this);
super.onDestroy();
}
@@ -54,52 +50,150 @@ public class YourActivity extends Activity {
```
-* 2. 通过Subscriber注解来标识事件接收对象中的接收方法
+* 2. Mark the receiving method of the Event-receiving Object with Subscriber annotation.
-```java
+```
public class YourActivity extends Activity {
+
// code ......
- // 接收方法,默认的tag,执行在UI线程
- @Subcriber
- private void updateTime(String time) {
- Log.e("", "### update time = " + time);
+ // 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);
}
- // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在UI线程
- @Subcriber(tag = "my_tag")
- private void updateTimeWithTag(String time) {
- Log.e("", "### update time with my_tag, time = " + time);
+ // 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);
}
- // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,
- // post函数在哪个线程执行,该函数就执行在哪个线程
- @Subcriber(tag = "my_tag", mode=ThreadMode.POST)
- private void updateTimeWithMode(String time) {
- Log.e("", "### update time with my_tag, time = " + time);
+ // 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);
}
- // 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在一个独立的线程
- @Subcriber(tag = "my_tag", mode = ThreadMode.ASYNC)
- private void updateTimeAsync(String time) {
- Log.e("", "### update time async , time = " + time + ", thread name = " + Thread.currentThread().getName());
+ // 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());
}
}
-```
- 接收函数使用tag来标识可接收的事件类型,与BroadcastReceiver中指定action是一样的,这样可以精准的投递消息。mode可以指定目标函数执行在哪个线程,默认会执行在UI线程,方便用户更新UI。目标方法执行耗时操作时,可以设置mode为ASYNC,使之执行在子线程中。
+```
+
+ 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.
+
-* 3. 在其他组件,例如Activity, Fragment,Service中发布事件
+* 3. To post an event in other components such as Activities, Fragments or Services.
-```java
- EventBus.getDefault().post("what's the time now ?");
+```
+
+ EventBus.getDefault().post(new User("android"));
// post a event with tag, the tag is like broadcast's action
- EventBus.getDefault().post(new Date().toLocaleString(), "my_tag");
-```
- 发布事件之后,注册了该事件类型的对象就会接收到响应的事件.
+ 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](lib/androideventbus-1.0.5.1.jar?raw=true "download")
+
+
+### 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](https://github.com/greenrobot/EventBus) | yes | It adopts name pattern which is efficient but inconvenient to use. |
+| [square's otto](https://github.com/square/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 ;
+}
+-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
```
diff --git a/Simple_Event_Test/AndroidManifest.xml b/Simple_Event_Test/AndroidManifest.xml
deleted file mode 100644
index 0108195..0000000
--- a/Simple_Event_Test/AndroidManifest.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Simple_Event_Test/proguard-project.txt b/Simple_Event_Test/proguard-project.txt
deleted file mode 100644
index f2fe155..0000000
--- a/Simple_Event_Test/proguard-project.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-# To enable ProGuard in your project, edit project.properties
-# to define the proguard.config property as described in that file.
-#
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in ${sdk.dir}/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the ProGuard
-# include property in project.properties.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
diff --git a/Simple_Event_Test/project.properties b/Simple_Event_Test/project.properties
deleted file mode 100644
index 3aedb2f..0000000
--- a/Simple_Event_Test/project.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-# This file is automatically generated by Android Tools.
-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
-#
-# This file must be checked in Version Control Systems.
-#
-# To customize properties used by the Ant build system edit
-# "ant.properties", and override values to adapt the script to your
-# project structure.
-#
-# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
-#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
-
-# Project target.
-target=android-10
-android.library.reference.1=..
diff --git a/Simple_Event_Test/res/drawable-hdpi/ic_launcher.png b/Simple_Event_Test/res/drawable-hdpi/ic_launcher.png
deleted file mode 100644
index 96a442e..0000000
Binary files a/Simple_Event_Test/res/drawable-hdpi/ic_launcher.png and /dev/null differ
diff --git a/Simple_Event_Test/res/drawable-ldpi/ic_launcher.png b/Simple_Event_Test/res/drawable-ldpi/ic_launcher.png
deleted file mode 100644
index 9923872..0000000
Binary files a/Simple_Event_Test/res/drawable-ldpi/ic_launcher.png and /dev/null differ
diff --git a/Simple_Event_Test/res/drawable-mdpi/ic_launcher.png b/Simple_Event_Test/res/drawable-mdpi/ic_launcher.png
deleted file mode 100644
index 359047d..0000000
Binary files a/Simple_Event_Test/res/drawable-mdpi/ic_launcher.png and /dev/null differ
diff --git a/Simple_Event_Test/res/drawable-xhdpi/ic_launcher.png b/Simple_Event_Test/res/drawable-xhdpi/ic_launcher.png
deleted file mode 100644
index 71c6d76..0000000
Binary files a/Simple_Event_Test/res/drawable-xhdpi/ic_launcher.png and /dev/null differ
diff --git a/Simple_Event_Test/res/values/strings.xml b/Simple_Event_Test/res/values/strings.xml
deleted file mode 100644
index 7bbdda0..0000000
--- a/Simple_Event_Test/res/values/strings.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
- Simple_Event_TestTest
-
-
diff --git a/Simple_Event_Test/src/org/simple/eventbus/test/EventBusTest.java b/Simple_Event_Test/src/org/simple/eventbus/test/EventBusTest.java
deleted file mode 100644
index fca713c..0000000
--- a/Simple_Event_Test/src/org/simple/eventbus/test/EventBusTest.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2014-2015 Umeng, Inc
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package org.simple.eventbus.test;
-
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import org.simple.eventbus.EventBus;
-import org.simple.eventbus.EventType;
-import org.simple.eventbus.test.mock.MockSubcriber;
-import org.simple.eventbus.test.mock.Person;
-import org.simple.eventbus.test.mock.SingleSubscriber;
-
-/**
- * @author mrsimple
- */
-public class EventBusTest extends AndroidTestCase {
-
- EventBus bus = EventBus.getDefault();
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- /**
- *
- */
- public void testRepeatRegister() {
- MockSubcriber mockActivity = new MockSubcriber();
- for (int i = 0; i < 10; i++) {
- // 测试重复注册一个对象
- bus.register(mockActivity);
- }
-
- // 类型为Person的有效注册函数为2个.
- assertEquals(2, bus.getSubscriptions(new EventType(Person.class)).size());
- // Object类型的函数为1一个
- assertEquals(1, bus.getSubscriptions(new EventType(Object.class)).size());
- }
-
- /**
- *
- */
- public void testRepeatRegisterWithTag() {
- MockSubcriber mockActivity = new MockSubcriber();
- for (int i = 0; i < 10; i++) {
- // 测试重复注册一个对象
- bus.register(mockActivity);
- }
-
- // 类型为Person且tag为"test"的有效注册函数为1个.
- assertEquals(1, bus.getSubscriptions(new EventType(Person.class, "test")).size());
-
- // 类型为Person且tag为"another"的有效注册函数为1个.
- assertEquals(1, bus.getSubscriptions(new EventType(Person.class, "another")).size());
- }
-
- /**
- *
- */
- public void testSubscribeAndPost() {
- MockSubcriber mockActivity = new MockSubcriber();
- // 正常注册与发布
- bus.register(mockActivity);
- bus.post(new Person("mr.simple"));
-
- // 移除对象
- bus.unregister(mockActivity);
- // 移除对象之后post不会出现问题
- bus.post(new Person("mr.simple"));
- // 移除对象测试
- assertEquals(0, bus.getSubscriptions(new EventType(Person.class)).size());
- assertEquals(0, bus.getSubscriptions(new EventType(Object.class)).size());
- }
-
- public void testRegisterNull() {
- bus.register(null);
- }
-
- public void testUnRegisterNull() {
- bus.unregister(null);
- }
-
- /**
- *
- */
- public void testPerformence() {
- long start = System.nanoTime();
- for (int i = 0; i < 1000; i++) {
- SingleSubscriber subscriber = new SingleSubscriber();
- bus.register(subscriber);
- }
- long end = System.nanoTime();
- Log.d(getName(), "### register 1000 subscriber, time = " + (end - start) + " ns, "
- + (end - start) / 1 * 1e6 + " ms");
-
- assertEquals(1000, bus.getSubscriptions(new EventType(Object.class)).size());
- }
-
-}
diff --git a/Simple_Event_Test/src/org/simple/eventbus/test/mock/MockSubcriber.java b/Simple_Event_Test/src/org/simple/eventbus/test/mock/MockSubcriber.java
deleted file mode 100644
index 70fbffa..0000000
--- a/Simple_Event_Test/src/org/simple/eventbus/test/mock/MockSubcriber.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2014-2015 Umeng, Inc
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package org.simple.eventbus.test.mock;
-
-import org.simple.eventbus.Subcriber;
-
-/**
- * @author mrsimple
- */
-public class MockSubcriber {
-
- @Subcriber
- void onEventNoParam() {
- }
-
- @Subcriber
- void onEventTwoParam(Person person, int id) {
-
- }
-
- @Subcriber
- void onEvent(Person person) {
- System.out.println("invoke onEvent(Person person) in " + this.getClass().getName());
- System.out.println("person name = " + person.name);
- }
-
- /**
- * 参数相同,函数名不同
- *
- * @param person
- */
- @Subcriber
- void addPerson(Person person) {
- System.out.println("invoke addPerson(Person person) in " + this.getClass().getName());
- System.out.println("person name = " + person.name);
- }
-
- /**
- * test tag
- *
- * @param person
- */
- @Subcriber(tag = "test")
- void methodWithTag(Person person) {
-
- }
-
- /**
- * another tag
- *
- * @param person
- */
- @Subcriber(tag = "another")
- void methodWithAnotherTag(Person person) {
-
- }
-
- /**
- * 同名函数,但是参数不同
- *
- * @param object
- */
- @Subcriber
- void onEvent(Object object) {
- System.out.println("invoke onEvent(Person person) in " + this.getClass().getName());
- }
-}
diff --git a/Simple_eventbus_demo/AndroidManifest.xml b/Simple_eventbus_demo/AndroidManifest.xml
deleted file mode 100644
index 648e774..0000000
--- a/Simple_eventbus_demo/AndroidManifest.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Simple_eventbus_demo/ic_launcher-web.png b/Simple_eventbus_demo/ic_launcher-web.png
deleted file mode 100644
index a18cbb4..0000000
Binary files a/Simple_eventbus_demo/ic_launcher-web.png and /dev/null differ
diff --git a/Simple_eventbus_demo/libs/android-support-v4.jar b/Simple_eventbus_demo/libs/android-support-v4.jar
deleted file mode 100644
index 4ebdaa9..0000000
Binary files a/Simple_eventbus_demo/libs/android-support-v4.jar and /dev/null differ
diff --git a/Simple_eventbus_demo/proguard-project.txt b/Simple_eventbus_demo/proguard-project.txt
deleted file mode 100644
index f2fe155..0000000
--- a/Simple_eventbus_demo/proguard-project.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-# To enable ProGuard in your project, edit project.properties
-# to define the proguard.config property as described in that file.
-#
-# Add project specific ProGuard rules here.
-# By default, the flags in this file are appended to flags specified
-# in ${sdk.dir}/tools/proguard/proguard-android.txt
-# You can edit the include path and order by changing the ProGuard
-# include property in project.properties.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# Add any project specific keep options here:
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
diff --git a/Simple_eventbus_demo/project.properties b/Simple_eventbus_demo/project.properties
deleted file mode 100644
index 3aedb2f..0000000
--- a/Simple_eventbus_demo/project.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-# This file is automatically generated by Android Tools.
-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
-#
-# This file must be checked in Version Control Systems.
-#
-# To customize properties used by the Ant build system edit
-# "ant.properties", and override values to adapt the script to your
-# project structure.
-#
-# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
-#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
-
-# Project target.
-target=android-10
-android.library.reference.1=..
diff --git a/Simple_eventbus_demo/res/drawable-xhdpi/event_bus.png b/Simple_eventbus_demo/res/drawable-xhdpi/event_bus.png
deleted file mode 100644
index 0c6e5a2..0000000
Binary files a/Simple_eventbus_demo/res/drawable-xhdpi/event_bus.png and /dev/null differ
diff --git a/Simple_eventbus_demo/res/drawable-xhdpi/ic_launcher.png b/Simple_eventbus_demo/res/drawable-xhdpi/ic_launcher.png
deleted file mode 100644
index d4fb7cd..0000000
Binary files a/Simple_eventbus_demo/res/drawable-xhdpi/ic_launcher.png and /dev/null differ
diff --git a/Simple_eventbus_demo/res/drawable-xxhdpi/ic_launcher.png b/Simple_eventbus_demo/res/drawable-xxhdpi/ic_launcher.png
deleted file mode 100644
index 85a6081..0000000
Binary files a/Simple_eventbus_demo/res/drawable-xxhdpi/ic_launcher.png and /dev/null differ
diff --git a/Simple_eventbus_demo/res/values/strings.xml b/Simple_eventbus_demo/res/values/strings.xml
deleted file mode 100644
index 448edc3..0000000
--- a/Simple_eventbus_demo/res/values/strings.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
- EventbusDemo
- remove
- add
- async
- this execute async, thread =
-
-
\ No newline at end of file
diff --git a/Simple_eventbus_demo/res/values/styles.xml b/Simple_eventbus_demo/res/values/styles.xml
deleted file mode 100644
index 6ce89c7..0000000
--- a/Simple_eventbus_demo/res/values/styles.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/Simple_eventbus_demo/src/org/simple/eventbus/demo/fragment/MenuFragment.java b/Simple_eventbus_demo/src/org/simple/eventbus/demo/fragment/MenuFragment.java
deleted file mode 100644
index 1a93b66..0000000
--- a/Simple_eventbus_demo/src/org/simple/eventbus/demo/fragment/MenuFragment.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2014-2015 Umeng, Inc
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package org.simple.eventbus.demo.fragment;
-
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.widget.TextView;
-
-import org.simple.eventbus.EventBus;
-import org.simple.eventbus.Subcriber;
-import org.simple.eventbus.ThreadMode;
-import org.simple.eventbus.demo.R;
-import org.simple.eventbus.demo.bean.Person;
-
-import java.util.Random;
-
-/**
- * @author mrsimple
- */
-public class MenuFragment extends Fragment {
-
- public static final String CLICK_TAG = "click_user";
- /**
- *
- */
- PostThread[] threads = new PostThread[4];
- /**
- * 显示被点击的用户名的TextView
- */
- TextView mUserNameTv;
- /**
- * Thread name TextView
- */
- TextView mThreadTv;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View rootView = inflater.inflate(R.layout.menu_fragment, container, false);
-
- mUserNameTv = (TextView) rootView.findViewById(R.id.click_tv);
- mThreadTv = (TextView) rootView.findViewById(R.id.timer_tv);
-
- // 发布事件
- rootView.findViewById(R.id.my_post_button).setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
- EventBus.getDefault().post(new Person("Mr.Simple" + new Random().nextInt(100)));
- }
- });
-
- // 发布移除事件的按钮
- rootView.findViewById(R.id.my_remove_button).setOnClickListener(
- new OnClickListener() {
-
- @Override
- public void onClick(View v) {
- // 移除用户
- EventBus.getDefault().post(new Person("User - 1"),
- "remove");
- }
- });
-
- // 发布异步事件的按钮
- rootView.findViewById(R.id.my_post_async_event_button).setOnClickListener(
- new OnClickListener() {
-
- @Override
- public void onClick(View v) {
- // 将目标函数执行在异步线程中
- EventBus.getDefault().post(new Person("mr.simple-3"), "async");
- }
- });
-
- startThread();
-
- EventBus.getDefault().register(this);
- return rootView;
- }
-
- private void startThread() {
- for (int i = 0; i < 4; i++) {
- threads[i] = new PostThread(i);
- threads[i].start();
- }
- }
-
- @Subcriber(tag = CLICK_TAG)
- private void updateClickUserName(Person clickPerson) {
- mUserNameTv.setText(clickPerson.name);
- }
-
- /*
- * 模拟从异步线程发来的更新信息
- */
- @Subcriber
- private void updateTime(String name) {
- Log.e(getTag(), "### update time, thread = " + Thread.currentThread().getName());
-
- // 从哪个线程投递来的消息
- mThreadTv.setText("from " + name);
-
- // post 给TimerThread线程
- EventBus.getDefault().post("I am tom, ", "sayhello");
- }
-
- @Subcriber(mode = ThreadMode.POST)
- private void invokeInPostThread(String event) {
- Log.e(getTag(), "### invokeInPostThread invoke in thread = "
- + Thread.currentThread().getName());
- }
-
- @Override
- public void onDestroy() {
- for (PostThread timerThread : threads) {
- timerThread.interrupt();
- }
-
- EventBus.getDefault().unregister(this);
- super.onDestroy();
- }
-
- /**
- * @author mrsimple
- */
- class PostThread extends Thread {
-
- int mIndex;
-
- public PostThread(int index) {
- mIndex = index;
- setName("Thread - " + index);
-
- EventBus.getDefault().register(this);
- }
-
- /**
- * receiver msg from other thread
- *
- * @param name
- */
- @Subcriber(tag = "sayhello")
- private void hello(String name) {
- Log.d(getTag(), "### hello, " + name + " --> in " + getName());
- }
-
- @Override
- public void run() {
- Log.e(getTag(), "### queue : " + EventBus.getDefault().getEventQueue().hashCode()
- + ", bus = " + EventBus.getDefault());
-
- while (!this.isInterrupted()) {
- EventBus.getDefault().post(getName());
- try {
- Thread.sleep(500 * mIndex + 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- EventBus.getDefault().unregister(this);
- }
- }
-}
diff --git a/app/.gitignore b/app/.gitignore
new file mode 100644
index 0000000..42afabf
--- /dev/null
+++ b/app/.gitignore
@@ -0,0 +1 @@
+/build
\ No newline at end of file
diff --git a/app/build.gradle b/app/build.gradle
new file mode 100644
index 0000000..aeef32d
--- /dev/null
+++ b/app/build.gradle
@@ -0,0 +1,45 @@
+plugins {
+ id 'com.android.application'
+ id 'org.jetbrains.kotlin.android'
+}
+
+android {
+ namespace 'com.android.eventbus.demo'
+ compileSdk 33
+
+ defaultConfig {
+ applicationId "com.android.eventbus.demo"
+ minSdk 21
+ targetSdk 33
+ versionCode 1
+ versionName "1.0"
+
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ }
+ }
+ kotlinOptions {
+ jvmTarget = '1.8'
+ }
+ buildFeatures {
+ viewBinding true
+ }
+}
+
+dependencies {
+
+ implementation 'androidx.appcompat:appcompat:1.6.1'
+ implementation 'com.google.android.material:material:1.5.0'
+ implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
+ implementation project(":library")
+
+
+ testImplementation 'junit:junit:4.13.2'
+ androidTestImplementation 'androidx.test.ext:junit:1.1.5'
+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
+}
\ No newline at end of file
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
new file mode 100644
index 0000000..481bb43
--- /dev/null
+++ b/app/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
\ No newline at end of file
diff --git a/app/src/androidTest/java/com/android/eventbus/demo/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/android/eventbus/demo/ExampleInstrumentedTest.kt
new file mode 100644
index 0000000..476e9ba
--- /dev/null
+++ b/app/src/androidTest/java/com/android/eventbus/demo/ExampleInstrumentedTest.kt
@@ -0,0 +1,24 @@
+package com.android.eventbus.demo
+
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.ext.junit.runners.AndroidJUnit4
+
+import org.junit.Test
+import org.junit.runner.RunWith
+
+import org.junit.Assert.*
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+@RunWith(AndroidJUnit4::class)
+class ExampleInstrumentedTest {
+ @Test
+ fun useAppContext() {
+ // Context of the app under test.
+ val appContext = InstrumentationRegistry.getInstrumentation().targetContext
+ assertEquals("com.android.eventbus.demo", appContext.packageName)
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..4c55b9c
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/java/com/android/eventbus/demo/MainActivity.java b/app/src/main/java/com/android/eventbus/demo/MainActivity.java
new file mode 100644
index 0000000..8e9bb65
--- /dev/null
+++ b/app/src/main/java/com/android/eventbus/demo/MainActivity.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package com.android.eventbus.demo;
+
+import android.os.Bundle;
+
+import androidx.appcompat.app.AppCompatActivity;
+
+public class MainActivity extends AppCompatActivity {
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main_activity);
+ }
+}
diff --git a/Simple_eventbus_demo/src/org/simple/eventbus/demo/MainActivity.java b/app/src/main/java/com/android/eventbus/demo/StickyActivity.java
similarity index 62%
rename from Simple_eventbus_demo/src/org/simple/eventbus/demo/MainActivity.java
rename to app/src/main/java/com/android/eventbus/demo/StickyActivity.java
index 8fd4277..e1e4f86 100644
--- a/Simple_eventbus_demo/src/org/simple/eventbus/demo/MainActivity.java
+++ b/app/src/main/java/com/android/eventbus/demo/StickyActivity.java
@@ -22,44 +22,47 @@
* THE SOFTWARE.
*/
-package org.simple.eventbus.demo;
+package com.android.eventbus.demo;
+import android.app.Activity;
import android.os.Bundle;
-import android.support.v4.app.FragmentActivity;
import android.util.Log;
+import android.widget.TextView;
+
+import com.android.eventbus.demo.bean.User;
import org.simple.eventbus.EventBus;
-import org.simple.eventbus.Subcriber;
-import org.simple.eventbus.ThreadMode;
+import org.simple.eventbus.Subscriber;
+
+public class StickyActivity extends Activity {
+
+ TextView nameTv;
+ TextView ageTv;
-public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- setContentView(R.layout.main_activity);
- }
+ setContentView(R.layout.sticky_activity);
- @Override
- protected void onDestroy() {
+ nameTv = (TextView) findViewById(R.id.name_tv);
+ ageTv = (TextView) findViewById(R.id.age_tv);
- EventBus.getDefault().unregister(this);
- // TODO Auto-generated method stub
- super.onDestroy();
+ EventBus.getDefault().registerSticky(this);
}
- @Subcriber
- private void updateTime(String time) {
- Log.e("", "### update time = " + time);
- }
+ @Subscriber
+ private void onReceiveStickyEvent(User info) {
+ nameTv.setText(info.name);
+ ageTv.setText("age ----- 32");
- @Subcriber(tag = "my_tag")
- private void updateTimeWithTag(String time) {
- Log.e("", "### update time with my_tag, time = " + time);
+ Log.e("", "### 找到 接到sticky消息 " + info.name);
+ // 接受到事件之后可以手动移除Sticky事件
+ EventBus.getDefault().removeStickyEvent(info.getClass());
}
- @Subcriber(tag = "my_tag", mode = ThreadMode.ASYNC)
- private void updateTimeAsync(String time) {
- Log.e("", "### update time async , time = " + time);
+ @Override
+ protected void onDestroy() {
+ // EventBus.getDefault().unregister(this);
+ super.onDestroy();
}
-
}
diff --git a/Simple_Event_Test/src/org/simple/eventbus/test/mock/SingleSubscriber.java b/app/src/main/java/com/android/eventbus/demo/bean/StickyUser.java
similarity index 80%
rename from Simple_Event_Test/src/org/simple/eventbus/test/mock/SingleSubscriber.java
rename to app/src/main/java/com/android/eventbus/demo/bean/StickyUser.java
index 8a70444..bc05ee6 100644
--- a/Simple_Event_Test/src/org/simple/eventbus/test/mock/SingleSubscriber.java
+++ b/app/src/main/java/com/android/eventbus/demo/bean/StickyUser.java
@@ -22,16 +22,12 @@
* THE SOFTWARE.
*/
-package org.simple.eventbus.test.mock;
+package com.android.eventbus.demo.bean;
-import org.simple.eventbus.Subcriber;
+public class StickyUser extends User {
-/**
- * @author mrsimple
- */
-public class SingleSubscriber {
- @Subcriber
- void onEvent(Object event) {
- System.out.println("invoke onEvent(Object event) in " + this.getClass().getName());
+ public StickyUser(String aName) {
+ super(aName + " - Sticky");
}
+
}
diff --git a/app/src/main/java/com/android/eventbus/demo/bean/User.java b/app/src/main/java/com/android/eventbus/demo/bean/User.java
new file mode 100644
index 0000000..15c7c02
--- /dev/null
+++ b/app/src/main/java/com/android/eventbus/demo/bean/User.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package com.android.eventbus.demo.bean;
+
+public class User {
+ public String name;
+
+ public User(String aName) {
+ name = aName;
+ }
+
+ @Override
+ public String toString() {
+ return "Person [name=" + name + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ User other = (User) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+}
diff --git a/app/src/main/java/com/android/eventbus/demo/fragment/BaseFragment.java b/app/src/main/java/com/android/eventbus/demo/fragment/BaseFragment.java
new file mode 100644
index 0000000..c5eb255
--- /dev/null
+++ b/app/src/main/java/com/android/eventbus/demo/fragment/BaseFragment.java
@@ -0,0 +1,46 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2015 Umeng, Inc
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.android.eventbus.demo.fragment;
+
+import android.util.Log;
+
+import androidx.fragment.app.Fragment;
+
+import com.android.eventbus.demo.bean.User;
+
+import org.simple.eventbus.Subscriber;
+
+/**
+ * @author mrsimple
+ */
+public class BaseFragment extends Fragment {
+
+ static final String SUPER_TAG = "super_tag";
+
+ @Subscriber(tag = SUPER_TAG)
+ private void privateMethodInSuper(User user) {
+ Log.e(getTag(), "### supper private Method In Super invoked ( default tag ) ");
+ }
+}
diff --git a/Simple_eventbus_demo/src/org/simple/eventbus/demo/fragment/ConstactFragment.java b/app/src/main/java/com/android/eventbus/demo/fragment/ConstactFragment.java
similarity index 60%
rename from Simple_eventbus_demo/src/org/simple/eventbus/demo/fragment/ConstactFragment.java
rename to app/src/main/java/com/android/eventbus/demo/fragment/ConstactFragment.java
index aa9360e..cd01c27 100644
--- a/Simple_eventbus_demo/src/org/simple/eventbus/demo/fragment/ConstactFragment.java
+++ b/app/src/main/java/com/android/eventbus/demo/fragment/ConstactFragment.java
@@ -1,46 +1,40 @@
/*
- * The MIT License (MIT)
+ * Copyright (C) 2015 Mr.Simple
*
- * Copyright (c) 2014-2015 Umeng, Inc
+ * 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
*
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
+ * 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.
*/
-package org.simple.eventbus.demo.fragment;
+package com.android.eventbus.demo.fragment;
import android.os.Bundle;
-import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
+import androidx.fragment.app.Fragment;
+
+import com.android.eventbus.demo.R;
+import com.android.eventbus.demo.bean.User;
+
import org.simple.eventbus.EventBus;
-import org.simple.eventbus.Subcriber;
+import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;
-import org.simple.eventbus.demo.R;
-import org.simple.eventbus.demo.bean.Person;
import java.util.LinkedList;
import java.util.List;
@@ -51,7 +45,7 @@
public class ConstactFragment extends Fragment {
BaseAdapter mAdapter;
- List mConstacts = new LinkedList();
+ List mConstacts = new LinkedList();
ListView mListView;
@Override
@@ -66,7 +60,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa
}
private void initListView() {
- mAdapter = new ArrayAdapter(getActivity(),
+ mAdapter = new ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, mConstacts);
mListView.setAdapter(mAdapter);
@@ -80,6 +74,22 @@ public void onItemClick(AdapterView> parent, View view, int position, long id)
});
}
+ @Subscriber
+ private void primitiveParam(int aInt) {
+ Toast.makeText(getActivity(), "int = " + aInt, Toast.LENGTH_SHORT).show();
+ }
+
+ @Subscriber
+ private void primitiveArrayParam(int[] aInt) {
+ Toast.makeText(getActivity(), "int array = " + aInt[0] + ", " + aInt[1], Toast.LENGTH_SHORT)
+ .show();
+ }
+
+ @Subscriber
+ private void primitiveParam(boolean ab) {
+ Toast.makeText(getActivity(), "boolean = " + ab, Toast.LENGTH_SHORT).show();
+ }
+
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
@@ -88,15 +98,15 @@ public void onDestroy() {
private void mockDatas() {
for (int i = 0; i < 6; i++) {
- mConstacts.add(new Person("User - " + i));
+ mConstacts.add(new User("User - " + i));
}
}
/**
* @param person
*/
- @Subcriber
- public void addPerson(Person person) {
+ @Subscriber
+ public void addPerson(User person) {
mConstacts.add(person);
mAdapter.notifyDataSetChanged();
}
@@ -106,19 +116,18 @@ public void addPerson(Person person) {
*
* @param person
*/
- @Subcriber(tag = "remove")
- private void addPersonPrivate(Person person) {
+ @Subscriber(tag = MenuFragment.REMOVE_TAG)
+ private void removePersonPrivate(User person) {
mConstacts.remove(person);
mAdapter.notifyDataSetChanged();
}
/**
* 执行在异步线程的函数
- *
- * @param event
+ * @param person
*/
- @Subcriber(tag = "async", mode = ThreadMode.ASYNC)
- private void asyncMethod(final Person person) {
+ @Subscriber(tag = MenuFragment.ASYNC_TAG, mode = ThreadMode.ASYNC)
+ private void asyncMethod(final User person) {
try {
final String threadName = Thread.currentThread().getName();
mListView.post(new Runnable() {
diff --git a/app/src/main/java/com/android/eventbus/demo/fragment/MenuFragment.java b/app/src/main/java/com/android/eventbus/demo/fragment/MenuFragment.java
new file mode 100644
index 0000000..ba31e97
--- /dev/null
+++ b/app/src/main/java/com/android/eventbus/demo/fragment/MenuFragment.java
@@ -0,0 +1,289 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package com.android.eventbus.demo.fragment;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import com.android.eventbus.demo.R;
+import com.android.eventbus.demo.StickyActivity;
+import com.android.eventbus.demo.bean.StickyUser;
+import com.android.eventbus.demo.bean.User;
+
+import org.simple.eventbus.EventBus;
+import org.simple.eventbus.Subscriber;
+import org.simple.eventbus.ThreadMode;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+
+/**
+ *
+ * 注意 : 如果发布的事件的参数类型是订阅的事件参数的子类,订阅函数默认也会被执行。例如你在订阅函数中订阅的是List类型的事件,
+ * 但是在发布时发布的是ArrayList的事件,
+ * 因此List是一个泛型抽象,而ArrayList才是具体的实现
+ * ,因此这种情况下订阅函数也会被执行。如果你需要订阅函数能够接收到的事件类型必须严格匹配 , 然后通过事件总线{@see
+ * EventBus#setMatchPolicy(org.simple.eventbus.matchpolicy.MatchPolicy)}设置匹配策略.
+ *
+ * @author mrsimple
+ */
+public class MenuFragment extends BaseFragment {
+
+ static final String CLICK_TAG = "click_user";
+ static final String THREAD_TAG = "sub_thread";
+ public static final String ASYNC_TAG = "async";
+ public static final String REMOVE_TAG = "remove";
+
+ /**
+ *
+ */
+ PostThread[] threads = new PostThread[4];
+ /**
+ * 显示被点击的用户名的TextView
+ */
+ TextView mUserNameTv;
+ /**
+ * Thread name TextView
+ */
+ TextView mThreadTv;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View rootView = inflater.inflate(R.layout.menu_fragment, container, false);
+
+ mUserNameTv = (TextView) rootView.findViewById(R.id.click_tv);
+ mThreadTv = (TextView) rootView.findViewById(R.id.timer_tv);
+
+ // 发布事件
+ rootView.findViewById(R.id.my_post_button).setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ EventBus.getDefault().post(new User("Mr.Simple" + new Random().nextInt(100)));
+ }
+ });
+
+ // 发布移除事件的按钮
+ rootView.findViewById(R.id.my_remove_button).setOnClickListener(
+ new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ // 移除用户
+ EventBus.getDefault().post(new User("User - 1"), REMOVE_TAG);
+ }
+ });
+
+ // 发布异步事件的按钮
+ rootView.findViewById(R.id.my_post_async_event_button).setOnClickListener(
+ new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ // 将目标函数执行在异步线程中
+ EventBus.getDefault().post(new User("async-user"), ASYNC_TAG);
+ }
+ });
+
+ // 发布事件,传递的是List数据
+ rootView.findViewById(R.id.my_post_list_btn).setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ postListData();
+ }
+ });
+
+ // 发布事件,调用的是父类中的函数
+ rootView.findViewById(R.id.my_post_to_supper_btn).setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ postEventToSuper();
+ }
+ });
+
+ // 发布事件,将事件投递到子线程中
+ rootView.findViewById(R.id.my_post_to_thread_btn).setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ // post 给PostThread线程
+ EventBus.getDefault().post("I am MainThread", THREAD_TAG);
+ }
+ });
+
+ // 发布事件,事件类型为原始类型,比如int, boolean, float等
+ rootView.findViewById(R.id.post_primitive_btn).setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ EventBus.getDefault().post(12345);
+ // 整型数组
+ EventBus.getDefault().post(new int[] {
+ 12, 24
+ });
+ EventBus.getDefault().post(true);
+ }
+ });
+
+ startThreads();
+
+ EventBus.getDefault().register(this);
+
+ rootView.findViewById(R.id.post_sticky_tv).setOnClickListener(new OnClickListener() {
+
+ @Override
+ public void onClick(View v) {
+ // 发布Sticky事件
+ EventBus.getDefault().postSticky(new StickyUser("我来自Sticky事件 - StickyUser类"));
+
+ // 跳转页面
+ Intent intent = new Intent(getActivity(), StickyActivity.class);
+ startActivity(intent);
+ }
+ });
+ return rootView;
+ }
+ @Override
+ public void onDestroy() {
+ EventBus.getDefault().unregister(this);
+ super.onDestroy();
+ }
+
+ /**
+ * start post threads
+ */
+ private void startThreads() {
+ for (int i = 0; i < 4; i++) {
+ threads[i] = new PostThread(i);
+ threads[i].start();
+ }
+ }
+
+ /**
+ * 发布参数是List类型的事件, 接收函数为@{@see #subcribeList(List)}
+ */
+ private void postListData() {
+ List userLisr = new ArrayList();
+ for (int i = 0; i < 5; i++) {
+ userLisr.add(new User("user - " + i));
+ }
+
+ EventBus.getDefault().post(userLisr);
+ }
+
+ @Subscriber
+ private void subcribeList(List users) {
+ for (int i = 0; i < users.size(); i++) {
+ Log.e(getTag(), "### user name = " + users.get(i));
+ }
+ }
+
+ /**
+ * 订阅点击事件,该事件是从{@see ConstactFragment}中的ListView点击某个项时发布的
+ *
+ * @param clickPerson
+ */
+ @Subscriber(tag = CLICK_TAG)
+ private void updateClickUserName(User clickPerson) {
+ mUserNameTv.setText(clickPerson.name);
+ }
+
+ /**
+ * 模拟从异步线程发来的更新信息, {@link PostThread#run()}
+ */
+ @Subscriber
+ private void receiveFrom(String name) {
+ // 从哪个线程投递来的消息
+ mThreadTv.setText("from " + name);
+ }
+
+ /**
+ * 接受参数类型为String的事件,执行在发布事件的线程. {@link PostThread#run()}
+ *
+ * @param event
+ */
+ @Subscriber(mode = ThreadMode.POST)
+ private void invokeInPostThread(String event) {
+ Log.e(getTag(), "### invokeInPostThread invoke in thread = "
+ + Thread.currentThread().getName());
+ }
+
+ /**
+ * 发布一个消息,接收函数在BaseFragment中
+ */
+ private void postEventToSuper() {
+ EventBus.getDefault().post(new User("super"), SUPER_TAG);
+ }
+
+ /**
+ * 投递线程,不断地给主线程投递消息,同时也接受主线程投递过来的消息
+ *
+ * @author mrsimple
+ */
+ class PostThread extends Thread {
+
+ int mIndex;
+
+ public PostThread(int index) {
+ mIndex = index;
+ setName("Thread - " + index);
+ // 线程本身也注册到事件总线中,接收从主线程发布的事件
+ EventBus.getDefault().register(this);
+ }
+
+ /**
+ * receiver msg from other thread
+ *
+ * @param name
+ */
+ @Subscriber(tag = THREAD_TAG)
+ private void sayHello(String name) {
+ Log.d(getTag(), "### hello, " + name + " --> in " + getName());
+ }
+
+ @Override
+ public void run() {
+ while (!this.isInterrupted()) {
+ // 从子线程发布消息
+ EventBus.getDefault().post(getName());
+
+ try {
+ Thread.sleep(1000 * mIndex + 3000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
new file mode 100644
index 0000000..2b068d1
--- /dev/null
+++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..07d5da9
--- /dev/null
+++ b/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,170 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/include_sticky_activity.xml b/app/src/main/res/layout/include_sticky_activity.xml
new file mode 100755
index 0000000..19a8b04
--- /dev/null
+++ b/app/src/main/res/layout/include_sticky_activity.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Simple_eventbus_demo/res/layout/list_fragment.xml b/app/src/main/res/layout/list_fragment.xml
similarity index 100%
rename from Simple_eventbus_demo/res/layout/list_fragment.xml
rename to app/src/main/res/layout/list_fragment.xml
diff --git a/Simple_eventbus_demo/res/layout/main_activity.xml b/app/src/main/res/layout/main_activity.xml
similarity index 79%
rename from Simple_eventbus_demo/res/layout/main_activity.xml
rename to app/src/main/res/layout/main_activity.xml
index ccf9180..37183c4 100755
--- a/Simple_eventbus_demo/res/layout/main_activity.xml
+++ b/app/src/main/res/layout/main_activity.xml
@@ -8,14 +8,14 @@
diff --git a/Simple_eventbus_demo/res/layout/menu_fragment.xml b/app/src/main/res/layout/menu_fragment.xml
similarity index 50%
rename from Simple_eventbus_demo/res/layout/menu_fragment.xml
rename to app/src/main/res/layout/menu_fragment.xml
index 3b68ddc..76914ce 100755
--- a/Simple_eventbus_demo/res/layout/menu_fragment.xml
+++ b/app/src/main/res/layout/menu_fragment.xml
@@ -23,11 +23,36 @@
android:layout_height="wrap_content"
android:text="@string/post_async" />
+
+
+
+
+
+
+
+
+ android:layout_marginTop="20dp"
+ android:text="@string/user_click_hint" />
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/sticky_activity.xml b/app/src/main/res/layout/sticky_activity.xml
new file mode 100755
index 0000000..dd407ee
--- /dev/null
+++ b/app/src/main/res/layout/sticky_activity.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/test_sticky_activity.xml b/app/src/main/res/layout/test_sticky_activity.xml
new file mode 100755
index 0000000..f2cba9a
--- /dev/null
+++ b/app/src/main/res/layout/test_sticky_activity.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..eca70cf
--- /dev/null
+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..eca70cf
--- /dev/null
+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v33/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v33/ic_launcher.xml
new file mode 100644
index 0000000..6f3b755
--- /dev/null
+++ b/app/src/main/res/mipmap-anydpi-v33/ic_launcher.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp
new file mode 100644
index 0000000..c209e78
Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
new file mode 100644
index 0000000..b2dfe3d
Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp
new file mode 100644
index 0000000..4f0f1d6
Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
new file mode 100644
index 0000000..62b611d
Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
new file mode 100644
index 0000000..948a307
Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
new file mode 100644
index 0000000..1b9a695
Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
new file mode 100644
index 0000000..28d4b77
Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
new file mode 100644
index 0000000..9287f50
Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
new file mode 100644
index 0000000..aa7d642
Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
new file mode 100644
index 0000000..9126ae3
Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ
diff --git a/app/src/main/res/values-land/dimens.xml b/app/src/main/res/values-land/dimens.xml
new file mode 100644
index 0000000..22d7f00
--- /dev/null
+++ b/app/src/main/res/values-land/dimens.xml
@@ -0,0 +1,3 @@
+
+ 48dp
+
\ No newline at end of file
diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml
new file mode 100644
index 0000000..15e703e
--- /dev/null
+++ b/app/src/main/res/values-night/themes.xml
@@ -0,0 +1,7 @@
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/values-v29/themes.xml b/app/src/main/res/values-v29/themes.xml
new file mode 100644
index 0000000..3981268
--- /dev/null
+++ b/app/src/main/res/values-v29/themes.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/values-w1240dp/dimens.xml b/app/src/main/res/values-w1240dp/dimens.xml
new file mode 100644
index 0000000..d73f4a3
--- /dev/null
+++ b/app/src/main/res/values-w1240dp/dimens.xml
@@ -0,0 +1,3 @@
+
+ 200dp
+
\ No newline at end of file
diff --git a/app/src/main/res/values-w600dp/dimens.xml b/app/src/main/res/values-w600dp/dimens.xml
new file mode 100644
index 0000000..22d7f00
--- /dev/null
+++ b/app/src/main/res/values-w600dp/dimens.xml
@@ -0,0 +1,3 @@
+
+ 48dp
+
\ No newline at end of file
diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..c8524cd
--- /dev/null
+++ b/app/src/main/res/values/colors.xml
@@ -0,0 +1,5 @@
+
+
+ #FF000000
+ #FFFFFFFF
+
\ No newline at end of file
diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..125df87
--- /dev/null
+++ b/app/src/main/res/values/dimens.xml
@@ -0,0 +1,3 @@
+
+ 16dp
+
\ No newline at end of file
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..4d02a8b
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,15 @@
+
+
+ EventbusDemo
+ remove
+ add
+ async
+ post to supper
+ post list data
+ no one click
+ post to thread
+ post primitive type
+ this execute async, thread =
+ post sticky
+
+
\ No newline at end of file
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
new file mode 100644
index 0000000..36170a4
--- /dev/null
+++ b/app/src/main/res/values/themes.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml
new file mode 100644
index 0000000..fa0f996
--- /dev/null
+++ b/app/src/main/res/xml/backup_rules.xml
@@ -0,0 +1,13 @@
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000..9ee9997
--- /dev/null
+++ b/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/test/java/com/android/eventbus/demo/ExampleUnitTest.kt b/app/src/test/java/com/android/eventbus/demo/ExampleUnitTest.kt
new file mode 100644
index 0000000..e63e6ba
--- /dev/null
+++ b/app/src/test/java/com/android/eventbus/demo/ExampleUnitTest.kt
@@ -0,0 +1,17 @@
+package com.android.eventbus.demo
+
+import org.junit.Test
+
+import org.junit.Assert.*
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * See [testing documentation](http://d.android.com/tools/testing).
+ */
+class ExampleUnitTest {
+ @Test
+ fun addition_isCorrect() {
+ assertEquals(4, 2 + 2)
+ }
+}
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..443cab9
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,6 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+plugins {
+ id 'com.android.application' version '7.4.1' apply false
+ id 'com.android.library' version '7.4.1' apply false
+ id 'org.jetbrains.kotlin.android' version '1.8.0' apply false
+}
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..3c5031e
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,23 @@
+# Project-wide Gradle settings.
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+# AndroidX package structure to make it clearer which packages are bundled with the
+# Android operating system, and which are packaged with your app's APK
+# https://developer.android.com/topic/libraries/support-library/androidx-rn
+android.useAndroidX=true
+# Kotlin code style for this project: "official" or "obsolete":
+kotlin.code.style=official
+# Enables namespacing of each library's R class so that its R class includes only the
+# resources declared in the library itself and none from the library's dependencies,
+# thereby reducing the size of the R class for that library
+android.nonTransitiveRClass=true
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..e708b1c
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..d3e2729
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Thu Jun 15 19:57:16 CST 2023
+distributionBase=GRADLE_USER_HOME
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
+distributionPath=wrapper/dists
+zipStorePath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..4f906e0
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,185 @@
+#!/usr/bin/env sh
+
+#
+# Copyright 2015 the original author or authors.
+#
+# 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
+#
+# https://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.
+#
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=`expr $i + 1`
+ done
+ case $i in
+ 0) set -- ;;
+ 1) set -- "$args0" ;;
+ 2) set -- "$args0" "$args1" ;;
+ 3) set -- "$args0" "$args1" "$args2" ;;
+ 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=`save "$@"`
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..ac1b06f
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,89 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/lib/androideventbus-1.0.5.1.jar b/lib/androideventbus-1.0.5.1.jar
new file mode 100644
index 0000000..146e186
Binary files /dev/null and b/lib/androideventbus-1.0.5.1.jar differ
diff --git a/lib/androideventbus-1.0.5.jar b/lib/androideventbus-1.0.5.jar
new file mode 100644
index 0000000..8c7aebf
Binary files /dev/null and b/lib/androideventbus-1.0.5.jar differ
diff --git a/library/.gitignore b/library/.gitignore
new file mode 100644
index 0000000..42afabf
--- /dev/null
+++ b/library/.gitignore
@@ -0,0 +1 @@
+/build
\ No newline at end of file
diff --git a/library/build.gradle b/library/build.gradle
new file mode 100644
index 0000000..37cbeb0
--- /dev/null
+++ b/library/build.gradle
@@ -0,0 +1,36 @@
+plugins {
+ id 'com.android.library'
+}
+
+android {
+ namespace 'com.android.eventbus.library'
+ compileSdk 33
+
+ defaultConfig {
+ minSdk 21
+ targetSdk 33
+
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ consumerProguardFiles "consumer-rules.pro"
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ }
+ }
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+}
+
+dependencies {
+
+ implementation 'androidx.appcompat:appcompat:1.6.1'
+ implementation 'com.google.android.material:material:1.9.0'
+ testImplementation 'junit:junit:4.13.2'
+ androidTestImplementation 'androidx.test.ext:junit:1.1.5'
+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
+}
\ No newline at end of file
diff --git a/library/consumer-rules.pro b/library/consumer-rules.pro
new file mode 100644
index 0000000..e69de29
diff --git a/library/proguard-rules.pro b/library/proguard-rules.pro
new file mode 100644
index 0000000..481bb43
--- /dev/null
+++ b/library/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
\ No newline at end of file
diff --git a/library/src/androidTest/java/com/android/eventbus/library/ExampleInstrumentedTest.java b/library/src/androidTest/java/com/android/eventbus/library/ExampleInstrumentedTest.java
new file mode 100644
index 0000000..8a7c5b9
--- /dev/null
+++ b/library/src/androidTest/java/com/android/eventbus/library/ExampleInstrumentedTest.java
@@ -0,0 +1,26 @@
+package com.android.eventbus.library;
+
+import android.content.Context;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * @see Testing documentation
+ */
+@RunWith(AndroidJUnit4.class)
+public class ExampleInstrumentedTest {
+ @Test
+ public void useAppContext() {
+ // Context of the app under test.
+ Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+ assertEquals("com.android.eventbus.library.test", appContext.getPackageName());
+ }
+}
\ No newline at end of file
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/DefaultMatchPolicyTest.java b/library/src/androidTest/java/org/simple/eventbus/test/DefaultMatchPolicyTest.java
new file mode 100644
index 0000000..849eb08
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/DefaultMatchPolicyTest.java
@@ -0,0 +1,88 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2015 Umeng, Inc
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package org.simple.eventbus.test;
+
+import static junit.framework.TestCase.assertEquals;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import junit.framework.TestCase;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.simple.eventbus.EventBus;
+import org.simple.eventbus.EventType;
+import org.simple.eventbus.Subscriber;
+import org.simple.eventbus.matchpolicy.DefaultMatchPolicy;
+import org.simple.eventbus.matchpolicy.MatchPolicy;
+import org.simple.eventbus.test.mock.User;
+
+import java.util.List;
+
+/**
+ * 注意 : 在发布事件时会查找与该事件匹配的订阅函数,默认的查找器会构造该事件父类的EventType,发布一个事件可能会引起多个事件。
+ *
+ * @author mrsimple
+ */
+@RunWith(AndroidJUnit4.class)
+public class DefaultMatchPolicyTest {
+
+ @Before
+ public void setUp() throws Exception {
+ EventBus.getDefault().register(this);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ EventBus.getDefault().unregister(this);
+ }
+
+ @Subscriber
+ private void whatEver(User user) {
+
+ }
+
+ @Subscriber
+ private void singleObjectParam(Object obj) {
+
+ }
+
+ @Test
+ public void testFindMatchMethod() {
+ MatchPolicy policy = new DefaultMatchPolicy();
+ List types = policy.findMatchEventTypes(new EventType(User.class,
+ EventType.DEFAULT_TAG), new User("org/simple/eventbus/test"));
+ assertEquals(2, types.size());
+
+ types.clear();
+
+ // 发布一个Object事件
+ types = policy.findMatchEventTypes(new EventType(Object.class,
+ EventType.DEFAULT_TAG), new Object());
+ assertEquals(1, types.size());
+ }
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/EventBusTest.java b/library/src/androidTest/java/org/simple/eventbus/test/EventBusTest.java
new file mode 100644
index 0000000..152d389
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/EventBusTest.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package org.simple.eventbus.test;
+
+import android.util.Log;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import junit.framework.TestCase;
+
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.simple.eventbus.EventBus;
+import org.simple.eventbus.EventType;
+import org.simple.eventbus.Subscription;
+import org.simple.eventbus.test.mock.MockSubcriber;
+import org.simple.eventbus.test.mock.SingleSubscriber;
+import org.simple.eventbus.test.mock.StickySubscriber;
+import org.simple.eventbus.test.mock.User;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * @author mrsimple
+ */
+@RunWith(AndroidJUnit4.class)
+public class EventBusTest extends TestCase {
+
+ EventBus bus = EventBus.getDefault();
+
+ Map> mSubcriberMap = bus.getSubscriberMap();
+
+ @After
+ public void tearDown() throws Exception {
+ super.tearDown();
+ EventBus.getDefault().clear();
+ }
+
+ /**
+ * 获取某个事件的观察者列表
+ *
+ * @param event 事件类型
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public Collection getSubscriptions(EventType event) {
+ List result = mSubcriberMap.get(event);
+ return result != null ? result : Collections.EMPTY_LIST;
+ }
+
+ /**
+ * 获取已经注册的事件类型列表
+ *
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public Collection getEventTypes() {
+ Collection result = mSubcriberMap.keySet();
+ return result != null ? result : Collections.EMPTY_LIST;
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testRepeatRegister() {
+ MockSubcriber mockActivity = new MockSubcriber();
+ for (int i = 0; i < 10; i++) {
+ // 测试重复注册一个对象
+ bus.register(mockActivity);
+ }
+
+ // 类型为Person的有效注册函数为2个.
+ assertEquals(2, getSubscriptions(new EventType(User.class)).size());
+ // Object类型的函数为1一个
+ assertEquals(1, getSubscriptions(new EventType(Object.class)).size());
+ }
+
+ /**
+ *
+ */
+ @Test
+ public void testRepeatRegisterWithTag() {
+ MockSubcriber mockActivity = new MockSubcriber();
+ for (int i = 0; i < 10; i++) {
+ // 测试重复注册一个对象
+ bus.register(mockActivity);
+ }
+
+ // 类型为Person且tag为"test"的有效注册函数为1个.
+ assertEquals(1, getSubscriptions(new EventType(User.class, "org/simple/eventbus/test")).size());
+
+ // 类型为Person且tag为"another"的有效注册函数为1个.
+ assertEquals(1, getSubscriptions(new EventType(User.class, "another")).size());
+ }
+
+ @Test
+ public void testSubscribeAndPost() {
+ MockSubcriber mockActivity = new MockSubcriber();
+ // 正常注册与发布
+ bus.register(mockActivity);
+ bus.post(new User("mr.simple"));
+
+ // 移除对象
+ bus.unregister(mockActivity);
+ // 移除对象之后post不会出现问题
+ bus.post(new User("mr.simple"));
+ // 移除对象测试
+ assertEquals(0, getSubscriptions(new EventType(User.class)).size());
+ assertEquals(0, getSubscriptions(new EventType(Object.class)).size());
+ }
+
+ @Test
+ public void testRegisterNull() {
+ bus.register(null);
+ }
+
+ @Test
+ public void testUnRegisterNull() {
+ bus.unregister(null);
+ }
+
+ @Test
+ public void testStickyEvents() {
+ assertEquals(0, bus.getStickyEvents().size());
+ bus.postSticky("hello");
+ assertEquals(1, bus.getStickyEvents().size());
+ final String tag = "sticky";
+ bus.postSticky("world", tag);
+ assertEquals(2, bus.getStickyEvents().size());
+
+ assertEquals(1, bus.getStickyEvents().size());
+
+ bus.removeStickyEvent(String.class, tag);
+ assertEquals(0, bus.getStickyEvents().size());
+ }
+
+ @Test
+ public void testStickySubscriber() {
+ StickySubscriber subscriber = new StickySubscriber();
+ assertEquals(null, subscriber.mStickyName);
+ assertEquals(null, subscriber.mStickyTag);
+ // 未注册时发布事件,那么对象接收不到事件
+ bus.post("hello");
+ // 普通注册形式
+ bus.register(subscriber);
+ assertEquals(null, subscriber.mStickyName);
+ assertEquals(null, subscriber.mStickyTag);
+ bus.unregister(subscriber);
+
+ // post sticky事件
+ bus.postSticky("simple");
+ // 以sticky的形式注册
+ bus.registerSticky(subscriber);
+ // 接收到数据
+ assertEquals("simple", bus.removeStickyEvent(String.class).event);
+
+ // post sticky事件, 含有tag, 这里需要注意
+ bus.postSticky("simple_v2", "sticky_v2");
+ final EventType eventType = bus.removeStickyEvent(String.class, "sticky_v2");
+ assertEquals("simple_v2", eventType.event);
+ assertEquals("sticky_v2", eventType.tag);
+ }
+
+ @Test
+ public void testPerformence() {
+ long start = System.nanoTime();
+ for (int i = 0; i < 1000; i++) {
+ SingleSubscriber subscriber = new SingleSubscriber();
+ bus.register(subscriber);
+ }
+ long end = System.nanoTime();
+ Log.d(getName(), "### register 1000 subscriber, time = " + (end - start) + " ns, "
+ + (end - start) / 1 * 1e6 + " ms");
+
+ assertEquals(1000, getSubscriptions(new EventType(Object.class)).size());
+ }
+
+}
diff --git a/Simple_Event_Test/src/org/simple/eventbus/test/EventTypeTest.java b/library/src/androidTest/java/org/simple/eventbus/test/EventTypeTest.java
similarity index 57%
rename from Simple_Event_Test/src/org/simple/eventbus/test/EventTypeTest.java
rename to library/src/androidTest/java/org/simple/eventbus/test/EventTypeTest.java
index 783ea2d..cdefb19 100644
--- a/Simple_Event_Test/src/org/simple/eventbus/test/EventTypeTest.java
+++ b/library/src/androidTest/java/org/simple/eventbus/test/EventTypeTest.java
@@ -1,31 +1,29 @@
/*
- * The MIT License (MIT)
+ * Copyright (C) 2015 Mr.Simple
*
- * Copyright (c) 2014-2015 Umeng, Inc
+ * 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
*
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
+ * 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.
*/
package org.simple.eventbus.test;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.simple.eventbus.EventBus;
import org.simple.eventbus.EventType;
import java.util.HashMap;
@@ -34,19 +32,20 @@
/**
* @author mrsimple
*/
+@RunWith(AndroidJUnit4.class)
public class EventTypeTest extends TestCase {
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
+ @After
+ public void tearDown() throws Exception {
super.tearDown();
+
+ EventBus.getDefault().clear();
}
/**
* 检测EventType作为map的key的唯一性
*/
+ @Test
public void testKeysInMap() {
Map map = new HashMap();
String tag = "default";
@@ -61,6 +60,7 @@ public void testKeysInMap() {
/**
* 检测类型相同,tag不同的EventType的唯一性
*/
+ @Test
public void testDiffKeysInMap() {
Map map = new HashMap();
String tag = "default";
@@ -74,6 +74,7 @@ public void testDiffKeysInMap() {
/**
* 检测类型相同,tag不同的EventType的唯一性
*/
+ @Test
public void testDiffParamKeysInMap() {
Map map = new HashMap();
map.put(new EventType(String.class), "String");
@@ -87,4 +88,10 @@ public void testDiffParamKeysInMap() {
assertEquals(6, map.size());
}
+
+ @Test
+ public void testEquals() {
+ assertEquals(new EventType(String.class, "tag"), new EventType(String.class, "tag"));
+ assertFalse( new EventType(String.class, "tag").equals(new EventType(String.class, "s_tag")));
+ }
}
diff --git a/Simple_Event_Test/src/org/simple/eventbus/test/BusTestSuite.java b/library/src/androidTest/java/org/simple/eventbus/test/PrimitiveEventTest.java
similarity index 71%
rename from Simple_Event_Test/src/org/simple/eventbus/test/BusTestSuite.java
rename to library/src/androidTest/java/org/simple/eventbus/test/PrimitiveEventTest.java
index 60f5200..26cb852 100644
--- a/Simple_Event_Test/src/org/simple/eventbus/test/BusTestSuite.java
+++ b/library/src/androidTest/java/org/simple/eventbus/test/PrimitiveEventTest.java
@@ -24,20 +24,22 @@
package org.simple.eventbus.test;
-import android.test.suitebuilder.TestSuiteBuilder;
+import static junit.framework.TestCase.assertEquals;
-import junit.framework.Test;
-import junit.framework.TestSuite;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
-/**
- * @author mrsimple
- */
-public class BusTestSuite extends TestSuite {
- public static Test suite() {
- return new TestSuiteBuilder(BusTestSuite.class)
- .includePackages(
- "org.simple.eventbus.test.EventBusTest",
- "org.simple.eventbus.test.EventTypeTest")
- .build();
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class PrimitiveEventTest {
+
+ @Test
+ public void testPrimitiveType() {
+ paramInt(2);
+ }
+
+ public void paramInt(Object aParam) {
+ assertEquals(Integer.class, aParam.getClass());
}
}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/SubscriberMethodHunterTest.java b/library/src/androidTest/java/org/simple/eventbus/test/SubscriberMethodHunterTest.java
new file mode 100644
index 0000000..e04aba6
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/SubscriberMethodHunterTest.java
@@ -0,0 +1,70 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2015 Umeng, Inc
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package org.simple.eventbus.test;
+
+import static junit.framework.TestCase.assertEquals;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.simple.eventbus.EventBus;
+import org.simple.eventbus.EventType;
+import org.simple.eventbus.SubsciberMethodHunter;
+import org.simple.eventbus.Subscription;
+import org.simple.eventbus.test.mock.PrimitiveParamObject;
+
+import java.util.List;
+
+@RunWith(AndroidJUnit4.class)
+public class SubscriberMethodHunterTest {
+
+ SubsciberMethodHunter mHunter = new SubsciberMethodHunter(EventBus.getDefault()
+ .getSubscriberMap());
+
+ PrimitiveParamObject object = new PrimitiveParamObject();
+
+ @Before
+ public void setUp() throws Exception {
+ EventBus.getDefault().register(object);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ EventBus.getDefault().unregister(object);
+ }
+
+ @Test
+ public void testFindPrimitiveParamMethod() {
+ mHunter.findSubcribeMethods(object);
+ List subscriptions = EventBus.getDefault().getSubscriberMap()
+ .get(new EventType(Integer.class));
+ assertEquals(1, subscriptions.size());
+ assertEquals(object, subscriptions.get(0).subscriber.get());
+ }
+
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/ThreadModeTest.java b/library/src/androidTest/java/org/simple/eventbus/test/ThreadModeTest.java
new file mode 100644
index 0000000..be43097
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/ThreadModeTest.java
@@ -0,0 +1,110 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2015 Umeng, Inc
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package org.simple.eventbus.test;
+
+import static junit.framework.TestCase.assertEquals;
+
+import android.util.Log;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.simple.eventbus.EventBus;
+import org.simple.eventbus.Subscriber;
+import org.simple.eventbus.ThreadMode;
+import org.simple.eventbus.handler.AsyncEventHandler;
+import org.simple.eventbus.test.mock.User;
+
+@RunWith(AndroidJUnit4.class)
+public class ThreadModeTest {
+
+ private static final String MAIN_TAG = "main";
+ private static final String POST_TAG = "post";
+ private static final String ASYNC_TAG = "async";
+
+ Thread uiThread;
+
+ @Before
+ public void setUp() throws Exception {
+ uiThread = Thread.currentThread();
+ EventBus.getDefault().register(this);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ EventBus.getDefault().register(this);
+ EventBus.getDefault().clear();
+ }
+
+ @Test
+ public void testExecuteMainThread() {
+ EventBus.getDefault().post(new User("main-thread"), MAIN_TAG);
+ waitDispatchEvent();
+ }
+
+ @Subscriber(tag = MAIN_TAG)
+ private void executeOnUIThread(User user) {
+ assertEquals("main-thread", user.name);
+ // can not test main thread mode
+ }
+
+ @Test
+ public void testExecutePostThread() {
+ EventBus.getDefault().post(new User("post-thread"), POST_TAG);
+
+ waitDispatchEvent();
+ }
+
+ @Subscriber(tag = POST_TAG, mode = ThreadMode.POST)
+ private void executeOnPostThread(User user) {
+ assertEquals("post-thread", user.name);
+ assertEquals(uiThread, Thread.currentThread());
+ }
+
+ @Test
+ public void testExecuteAsyncThread() {
+ EventBus.getDefault().post(new User("async-thread"), ASYNC_TAG);
+ waitDispatchEvent();
+ }
+
+ @Subscriber(tag = ASYNC_TAG, mode = ThreadMode.ASYNC)
+ private void executeOnAsyncThread(User user) {
+ assertEquals("async-thread", user.name);
+ assertEquals(AsyncEventHandler.class.getSimpleName(), Thread.currentThread().getName());
+ }
+
+ private void waitDispatchEvent() {
+ synchronized (this) {
+ try {
+ wait(200);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/mock/MockSubcriber.java b/library/src/androidTest/java/org/simple/eventbus/test/mock/MockSubcriber.java
new file mode 100644
index 0000000..b4fec30
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/mock/MockSubcriber.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package org.simple.eventbus.test.mock;
+
+import org.simple.eventbus.Subscriber;
+
+/**
+ * @author mrsimple
+ */
+public class MockSubcriber {
+
+ @Subscriber
+ void onEventNoParam() {
+ }
+
+ @Subscriber
+ void onEventTwoParam(User person, int id) {
+
+ }
+
+ @Subscriber
+ void onEvent(User person) {
+ System.out.println("invoke onEvent(Person person) in " + this.getClass().getName());
+ System.out.println("person name = " + person.name);
+ }
+
+ /**
+ * 参数相同,函数名不同
+ *
+ * @param person
+ */
+ @Subscriber
+ void addPerson(User person) {
+ System.out.println("invoke addPerson(Person person) in " + this.getClass().getName());
+ System.out.println("person name = " + person.name);
+ }
+
+ /**
+ * test tag
+ *
+ * @param person
+ */
+ @Subscriber(tag = "org/simple/eventbus/test")
+ void methodWithTag(User person) {
+
+ }
+
+ /**
+ * another tag
+ *
+ * @param person
+ */
+ @Subscriber(tag = "another")
+ void methodWithAnotherTag(User person) {
+
+ }
+
+ /**
+ * 同名函数,但是参数不同
+ *
+ * @param object
+ */
+ @Subscriber
+ void onEvent(Object object) {
+ System.out.println("invoke onEvent(Person person) in " + this.getClass().getName());
+ }
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/mock/PrimitiveParamObject.java b/library/src/androidTest/java/org/simple/eventbus/test/mock/PrimitiveParamObject.java
new file mode 100644
index 0000000..570cfc8
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/mock/PrimitiveParamObject.java
@@ -0,0 +1,57 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2015 Umeng, Inc
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package org.simple.eventbus.test.mock;
+
+import org.simple.eventbus.Subscriber;
+
+/**
+ * @author mrsimple
+ */
+public class PrimitiveParamObject {
+ @Subscriber
+ public void intParam(int aInt) {
+
+ }
+
+ @Subscriber
+ public void booleanParam(boolean ab) {
+
+ }
+
+ @Subscriber
+ public void floatParam(float aFloat) {
+
+ }
+
+ @Subscriber
+ public void doubleParam(double aDouble) {
+
+ }
+
+ @Subscriber
+ public void intArrayParam(int[] ints) {
+
+ }
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/mock/SingleSubscriber.java b/library/src/androidTest/java/org/simple/eventbus/test/mock/SingleSubscriber.java
new file mode 100644
index 0000000..7b480fc
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/mock/SingleSubscriber.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package org.simple.eventbus.test.mock;
+
+import org.simple.eventbus.Subscriber;
+
+/**
+ * @author mrsimple
+ */
+public class SingleSubscriber {
+ @Subscriber
+ void onEvent(Object event) {
+ System.out.println("invoke onEvent(Object event) in " + this.getClass().getName());
+ }
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/mock/StickySubscriber.java b/library/src/androidTest/java/org/simple/eventbus/test/mock/StickySubscriber.java
new file mode 100644
index 0000000..e6a6ed6
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/mock/StickySubscriber.java
@@ -0,0 +1,46 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2015 Umeng, Inc
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package org.simple.eventbus.test.mock;
+
+import org.simple.eventbus.Subscriber;
+import org.simple.eventbus.ThreadMode;
+
+public class StickySubscriber {
+
+ public String mStickyName;
+ public String mStickyTag;
+
+ @Subscriber(mode=ThreadMode.POST)
+ protected void receiveStickyEvent(String name) {
+ mStickyName = name;
+ System.out.println("sticky name : " + name);
+ }
+
+ @Subscriber(tag = "sticky", mode=ThreadMode.POST)
+ protected void receiveStickyEventWithTag(String name) {
+ mStickyTag = "sticky";
+ System.out.println("sticky name : " + name);
+ }
+}
diff --git a/library/src/androidTest/java/org/simple/eventbus/test/mock/User.java b/library/src/androidTest/java/org/simple/eventbus/test/mock/User.java
new file mode 100644
index 0000000..7cf330b
--- /dev/null
+++ b/library/src/androidTest/java/org/simple/eventbus/test/mock/User.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package org.simple.eventbus.test.mock;
+
+/**
+ * @author mrsimple
+ */
+public class User {
+ public String name;
+
+ public User(String aName) {
+ name = aName;
+ }
+
+ @Override
+ public String toString() {
+ return "Person [name=" + name + "]";
+ }
+
+}
diff --git a/library/src/main/AndroidManifest.xml b/library/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..a5918e6
--- /dev/null
+++ b/library/src/main/AndroidManifest.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/library/src/main/java/org/simple/eventbus/EventBus.java b/library/src/main/java/org/simple/eventbus/EventBus.java
new file mode 100644
index 0000000..3eec945
--- /dev/null
+++ b/library/src/main/java/org/simple/eventbus/EventBus.java
@@ -0,0 +1,490 @@
+/*
+ * Copyright (C) 2015 Mr.Simple
+ *
+ * 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.
+ */
+
+package org.simple.eventbus;
+
+import android.util.Log;
+
+import org.simple.eventbus.handler.AsyncEventHandler;
+import org.simple.eventbus.handler.DefaultEventHandler;
+import org.simple.eventbus.handler.EventHandler;
+import org.simple.eventbus.handler.UIThreadEventHandler;
+import org.simple.eventbus.matchpolicy.DefaultMatchPolicy;
+import org.simple.eventbus.matchpolicy.MatchPolicy;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ *