Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 133 章 EventBus

目录

133.1. 添加 EventBus 依赖到项目Gradle文件
133.2. 快速开始一个演示例子
133.2.1. 创建 MessageEvent 类
133.2.2. Layout
133.2.3. Activity
133.3. Sticky Events
133.3.1. MainActivity
133.3.2. StickyActivity
133.3.3. MessageEvent
133.3.4. 删除粘性事件
133.4. 线程模型
133.5. 配置 EventBus
133.6. 事件优先级
133.7. 捕获异常事件

http://greenrobot.org/eventbus

在EventBus中主要有以下三个成员:

	
Event:事件,可以自定义为任意对象,类似Message类的作用;
Publisher:事件发布者,可以在任意线程、任意位置发布Event,已发布的Evnet则由EventBus进行分发;
Subscriber:事件订阅者,接收并处理事件,需要通过register(this)进行注册,而在类销毁时要使用unregister(this)方法解注册。每个Subscriber可以定义一个或多个事件处理方法,其方法名可以自定义,但需要添加@Subscribe的注解,并指明ThreadMode(不写默认为Posting)。	
	
	

133.1. 添加 EventBus 依赖到项目Gradle文件

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'
}