轉載聲明原創地址:http://blog.csdn.net/lsyz0021/article/details/51985307
30分鐘學會EventBus3.0詳解(一)(引入和初始化EventBus3.0)
30分鐘學會EventBus3.0詳解(二)(EventBus3.0的詳細使用)
前言
EventBus是greenrobot出品的非常優秀的基於發佈、訂閱模式的一套框架,很早就想寫篇文章介紹他的文章,可是一直也沒時間寫,今天就寫篇文章也算總結一下吧。
首先說說EventBus的優點:它是一個基於觀察者模式的事件發佈/訂閱框架,開發者可以通過極少的代碼去實現多個模塊之間的通信,而不需要以層層傳遞接口的形式去單獨構建通信橋樑。從而降低因多重回調導致的模塊間強耦合,同時避免產生大量內部類。它擁有使用方便,性能高,接入成本低和支持多線程的優點,實乃模塊解耦、代碼重構必備良藥。
它支持Activities, Fragments, Threads, Services之間的數據傳遞,這是他的官方原理圖。
EventBus3.0和之前的EventBus2.4使用上是有區別的,由於3.0使用了註解的方式,並且增加了“SubscriberInfoIndex”要比2.0的效率高出了很多,所以今天我們講解EventBus3.0的使用。
2017年3月13日文章修改(gradle2.2.0後的代碼生成)
由於gradle2.2.0修改了註解的生成方式,所以在eventbus3.0生成“MyEventBusIndex”也不相同。
在gradle2.2.0之前使用:android-apt
在gradle2.2.0之後使用:annotationProcessor
引入EventBus3.0
gradle2.2.0之前引入EventBus3.0
1、在app的build.gradle中的 dependencies 中添加的 EventBus3.0的依賴
compile 'org.greenrobot:eventbus:3.0.0'
2、如果你想開啓加速模式,你還需要配置eventbus-annotation-processor
(1)在dependencies 中添加
apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
(2)在dependencies的下方添加
apt {
arguments {
eventBusIndex "com.bandeng.MyEventBusIndex"
}
}
(3)配置plugin
apply plugin: 'com.neenbedankt.android-apt'
app的build.gradle中的配置圖
(4)最後這裏在project build.gradle配置
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
gradle2.2.0之後引入EventBus3.0
如果你使用的gradle2.2.0及更高版本,那麼就需要下面的方式引入Eventbus了,在build.gradle中配置如下
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : 'com.bandeng.MyEventBusIndex' ]
}
}
}
}
dependencies {
compile 'org.greenrobot:eventbus:3.0.0'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}
看圖配置生成加速的MyEventBusIndex類
設置完成後要記得rebuild一下
rebuild之後,我們就可以做在build目錄下看到MyEventBusIndex這個類了(如果還沒有生成的話,可以先將app運行到手機後再rebuild試試)
初始EventBus
EventBus有個獲取單利的方法EventBus.getDefault(),這樣就可以獲取EventBus對象了
EventBus.getDefault()
但是,如果我們還想要用加速模式,那麼就要先現在Application的onCreate()方法中調用下面的方法/**
* 作者: lcw on 2016/7/6.
* 博客: http://blog.csdn.net/lsyz0021/
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// 啓用EventBus3.0加速功能
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
}
}
然後在清單文件的Application節點下配置name爲
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:name=".MyApplication"
android:theme="@style/AppTheme">
<activity android:name=".activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activity.SecondActivity"/>
</application>
這樣我們再調用EventBus.getDefault()就開啓了加速模式了
EventBus.getDefault();
我在這裏寫了一個EventBus工具類,方便大家使用,可以參考一下。https://github.com/lsyz0021/EventBusUtils
30分鐘學會EventBus3.0詳解(一)(引入和初始化EventBus3.0)
30分鐘學會EventBus3.0詳解(二)(EventBus3.0的詳細使用)