EventBus 使用解析

来源:互联网 发布:java中局部变量 编辑:程序博客网 时间:2024/06/06 09:30

MVP 设置模式将View与Model交互解耦,EventBus则用来对程序组件进行解耦。使得两个类没有直接的依赖关系,把双向依赖变成了单向依赖,降低维护成本,避免各种callback。

1、添加依赖

compile 'org.greenrobot:eventbus:3.0.0'

如果需要使用索引增强Bus的速度,需要在app下的 build.gradle 中加入

apply plugin: 'com.android.application'android {    compileSdkVersion 25    buildToolsVersion "25.0.2"    defaultConfig {        applicationId "com.org.zl.myeventbusdemo"        minSdkVersion 15        targetSdkVersion 25        versionCode 1        versionName "1.0"        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }}//这里是Eventbus 依赖 2apply plugin: 'com.neenbedankt.android-apt'dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:25.1.0'    testCompile 'junit:junit:4.12'    //这里是Eventbus 依赖 3    compile 'org.greenrobot:eventbus:3.0.0'    //这里是Eventbus 依赖 4    apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'}//这里是Eventbus 依赖 5apt {    arguments {        eventBusIndex "com.bandeng.MyEventBusIndex"    }}

Demo 下的build.gradle 中加入

buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:2.2.2'        //这里是Eventbus 依赖  1        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

然后rebuild 项目

这里写图片描述

如果有,则加入索引成功。

Bus中有几个方法,很重要,看看具体作用

我在另一个界面发送一个子线程消息,一个UI线程消息

EventBus.getDefault().post(new EventMessage("这是主线程发送的",1));                //延时三秒发送子线程数据出去                new Thread(new Runnable() {                    @Override                    public void run() {                        try {                            Thread.sleep(3000);                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                        EventBus.getDefault().post(new EventMessage("这是子线程发送的",2));                    }                }).start();

我在接收界面写了接收代码,根据接收不同显示方式也不一样,如果是主线程,那么就更新界面,如果不是主线程,那么就Toast信息

if(isMainThread()){//如果是主线程,那么更新界面            switch (event.getNum()){                case 1:                    textView2.setTextColor(getResources().getColor(R.color.colorRed));                    textView2.setText(event.toString());                    break;                case 2:                    textView2.setTextColor(getResources().getColor(R.color.colorPrimaryDark));                    textView2.setText(event.toString());                    break;            }        }else{//如果不是就通知handle            str = event.toString();            handler.sendEmptyMessage(-1);        }

方法名随便都可以,关键是注解ThreadMode方式

/**     @Subscribe(threadMode = ThreadMode.MAIN)     不管从哪个线程发出的事件,都会在UI(主线程)线程执行     在这里可以更新UI的操作,不可以执行耗时的操作     */

这里写图片描述

可以看出来,不管是主线程还是子线程,都会可以更新UI界面。

 @Subscribe(threadMode = ThreadMode.POSTING)     事件从哪个线程发布出来的,就在哪个线程中执行     如果发送事件的线程是UI线程,则在UI线程执行,     如果发送事件的线程是子线程,则在该子线程中执行

这里写图片描述

主线程发的更新了界面,子线程发的,toast信息,

 @Subscribe(threadMode = ThreadMode.BACKGROUND)     如果发送事件的线程是UI线程,则重新创建新的子线程执行     不能执行更新UI的操作     如果发送事件的线程是子线程,则在该子线程中执行

这里写图片描述

不管主线程还是子线程发送的,都不能更新界面

 @Subscribe(threadMode = ThreadMode.ASYNC)     不管从哪个线程发出的事件,ASYNC模式都会创建一个新的子线程来执行     所以在这里不能执行更新UI的操作,可以执行耗时的操作

这里写图片描述

ThreadMode.BACKGROUND中的任务,一个接着一个去调用
ThreadMode.Async则会动态控制并发。

上面都是先订阅,后发布,然后订阅的人知道了
还有一个粘性事件,就是先发布,后订阅,订阅后也知道,先前发布了啥东西,但是不管先前发布了多少东西,订阅的人,只能知道最后一条消息。

0 0