目錄
http://greenrobot.org/eventbus
在EventBus中主要有以下三個成員:
Event:事件,可以自定義為任意對象,類似Message類的作用; Publisher:事件發佈者,可以在任意綫程、任意位置發佈Event,已發佈的Evnet則由EventBus進行分發; Subscriber:事件訂閲者,接收並處理事件,需要通過register(this)進行註冊,而在類銷毀時要使用unregister(this)方法解註冊。每個Subscriber可以定義一個或多個事件處理方法,其方法名可以自定義,但需要添加@Subscribe的註解,並指明ThreadMode(不寫預設為Posting)。
Gradle:
implementation 'org.greenrobot:eventbus:3.1.1'
完整的例子
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "cn.netkiller.eventbus"
minSdkVersion 26
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'org.greenrobot:eventbus:3.1.1'
}