關(guān)于EventBus3.0使用,你看這篇就夠了

作為一枚Android開(kāi)發(fā)者,關(guān)于EventBus相信應(yīng)該都聽(tīng)說(shuō)過(guò)。要是用過(guò)就請(qǐng)忽略本文,本文講得比較基礎(chǔ)。
要是沒(méi)用過(guò),建議你花兩分鐘看看。

目前EventBus最新版本是3.0,本demo基于3.0編寫(xiě)的。

GitHub : https://github.com/greenrobot/EventBus
官方文檔:http://greenrobot.org/eventbus/documentation

一、EventBus概述

EventBus是一個(gè)Android端優(yōu)化的publish/subscribe消息總線,簡(jiǎn)化了應(yīng)用程序內(nèi)各組件間、組件與后臺(tái)線程間的通信。

作為一個(gè)消息總線主要有三個(gè)組成部分:

  • 事件(Event)
  • 事件訂閱者(Subscriber)
  • 事件發(fā)布者(Publisher)


    官方提供的關(guān)系圖

二、EventBus用法

1、把EventBus依賴到項(xiàng)目

build.gradle添加引用

compile 'org.greenrobot:eventbus:3.0.0'

Maven

<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus</artifactId>
    <version>3.0.0</version>
</dependency>

或者直接下載EventBus 架包jar 放到項(xiàng)目中

2、構(gòu)造發(fā)送消息類,也就是發(fā)送的對(duì)象
public class MainMessage{

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
3、注冊(cè)/解除注冊(cè)

EventBus.getDefault().register(this);//注冊(cè)

EventBus.getDefault().unregister(this);//解除注冊(cè)
4 、發(fā)送消息
EventBus.getDefault().post(new MainMessage("你好,愛(ài)開(kāi)發(fā)");

ThreadMode總共四個(gè):

  • MAIN UI主線程

  • POSTING 默認(rèn)調(diào)用方式,在調(diào)用post方法的線程執(zhí)行,避免了線程切換,性能開(kāi)銷最少

  • BACKGROUND 如果調(diào)用post方法的線程不是主線程,則直接在該線程執(zhí)行。
    如果是主線程,則切換到后臺(tái)單例線程,多個(gè)方法公用同個(gè)后臺(tái)線程,按順序執(zhí)行,避免耗時(shí)操作

  • ASYNC 開(kāi)辟新獨(dú)立線程,用來(lái)執(zhí)行耗時(shí)操作,例如網(wǎng)絡(luò)訪問(wèn)。

來(lái)看一下源碼,ThreadMode也就一個(gè)枚舉,英文自己對(duì)照理解吧,不是很復(fù)雜

public enum ThreadMode {
    /**
     * Subscriber will be called in the same thread, which is posting the event. This is the default. Event delivery
     * implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for
     * simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers
     * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
     */
    POSTING,

    /**
     * Subscriber will be called in Android's main thread (sometimes referred to as UI thread). If the posting thread is
     * the main thread, event handler methods will be called directly. Event handlers using this mode must return
     * quickly to avoid blocking the main thread.
     */
    MAIN,

    /**
     * Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods
     * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
     * background thread, that will deliver all its events sequentially. Event handlers using this mode should try to
     * return quickly to avoid blocking the background thread.
     */
    BACKGROUND,

    /**
     * Event handler methods are called in a separate thread. This is always independent from the posting thread and the
     * main thread. Posting events never wait for event handler methods using this mode. Event handler methods should
     * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
     * of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus
     * uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.
     */
    ASYNC
}
5 、事件處理
//ui主線程中執(zhí)行  
@Subscribe(threadMode = ThreadMode.Main) 
 
public void onMainEventBus(MainMessage msg) {  
}

6、priority事件優(yōu)先級(jí)

//priority越大,級(jí)別越高
@Subscribe(threadMode = ThreadMode.MAIN,priority = 100) 
public void onEvent(MainMessage event) {
}
7、終止事件傳遞
// 注意中止事件傳遞,后續(xù)事件不在調(diào)用

@Subscribe
public void onEvent(MessageEvent event){
    EventBus.getDefault().cancelEventDelivery(event) ;
}

下面我們來(lái)看一個(gè)完整的demo
先看一下效果圖:


3.gif

新建兩個(gè)activity,分別為MainActivity和 SecondActivity

其中MainActivity來(lái)放了五個(gè)按鈕和一個(gè)文本框
SecondActivity只有一個(gè)按鈕,點(diǎn)擊按鈕通知MainActivity頁(yè)面更新。

看一下MainActivity主要代碼:

     /**
     * 主線程中執(zhí)行
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(MainMessage msg) {
        Log.e(TAG, msg.getMessage());
        tv_desc.setText(msg.getMessage());
    }

    /**
     * 后臺(tái)線程
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onBackgroundEventBus(BackgroundMessage msg) {
        Log.e(TAG, msg.getMessage());
    }

    /**
     * 異步線程
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onAsyncEventBus(AsyncMessage msg) {
        Log.e(TAG, msg.getMessage());

    }

    /**
     * 默認(rèn)情況,和發(fā)送事件在同一個(gè)線程
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onPostEventBus(PostingMessage msg) {

        Log.e(TAG, msg.getMessage());
    }

按鈕點(diǎn)擊事件

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnMain:
                EventBus.getDefault().post(new MainMessage("MainMessage"));
                break;
            case R.id.btnBackground:
                EventBus.getDefault().post(new BackgroundMessage("BackgroundMessage"));
                break;
            case R.id.btnAsync:
                EventBus.getDefault().post(new AsyncMessage("AsyncMessage"));
                break;
            case R.id.btnPosting:
                EventBus.getDefault().post(new PostingMessage("PostingMessage"));
                break;
            case R.id.btn1:
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
                break;

        }
    }

分別點(diǎn)擊前面四個(gè)按鈕時(shí)控制臺(tái)按順序輸出:

點(diǎn)擊前面四個(gè)按鈕時(shí)控制臺(tái)輸出

SecondActivity頁(yè)面點(diǎn)擊發(fā)送消息的事件

EventBus.getDefault().post(new MainMessage("傳遞信息:aikaifa"));

在MianActivity頁(yè)面我們就能接受到SecondActivity傳遞過(guò)來(lái)的信息了。
如果感興趣想跑一下項(xiàng)目,源碼請(qǐng)戳這里

[END]

我是洪生鵬,
熱衷旅行、寫(xiě)作,目前過(guò)著白天到工地搬磚、晚上寫(xiě)故事的生活。
希望今天的文章對(duì)你有幫助。
堅(jiān)持日更,一般會(huì)在晚上10點(diǎn)發(fā)文,歡迎交流。

優(yōu)質(zhì)文章推薦:

我也很愛(ài)面子

為什么有的人工作多年還是老樣子

程序員月薪多少才不會(huì)焦慮

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 項(xiàng)目到了一定階段會(huì)出現(xiàn)一種甜蜜的負(fù)擔(dān):業(yè)務(wù)的不斷發(fā)展與人員的流動(dòng)性越來(lái)越大,代碼維護(hù)與測(cè)試回歸流程越來(lái)越繁瑣。這個(gè)...
    fdacc6a1e764閱讀 3,342評(píng)論 0 6
  • 目錄 1.概述 2.實(shí)戰(zhàn) 1.基本框架搭建 2.新建一個(gè)類FirstEvent 3.在要接收消息的頁(yè)面注冊(cè)Even...
    慕涵盛華閱讀 10,631評(píng)論 2 16
  • 前言:EventBus出來(lái)已經(jīng)有一段時(shí)間了,github上面也有很多開(kāi)源項(xiàng)目中使用了EventBus。所以抽空學(xué)習(xí)...
    Kerry202閱讀 1,373評(píng)論 1 2
  • 前言 EventBus是greenrobot在Android平臺(tái)發(fā)布的一款以訂閱——發(fā)布模式為核心的開(kāi)源庫(kù)。Eve...
    丶藍(lán)天白云夢(mèng)閱讀 24,388評(píng)論 18 76
  • 無(wú)力的模仿談不上多喜歡 如果說(shuō)跟從是一種站隊(duì),那么模仿則成了無(wú)聲的表態(tài)。即我欣賞你,想要成為...
    崔朱月閱讀 258評(píng)論 0 1

友情鏈接更多精彩內(nèi)容