Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發自助餐:EventBus 事件框架快速上手

編輯:關於 Android 程式設計

配置 build.gradle

compile 'de.greenrobot:eventbus:2.4.0'

實例化 EventBus

eventBus=EventBus.builder().build();

註冊事件監聽

eventBus.register(this);
這裡的 this 就是事件的接收者(負責消費、處理事件)。

定義被傳遞的事件類

注意,這裡要定義一個類——這個類可以隨意定義,也可以直接複用現有的類。

 class Event{ public String result="default"; }

發送事件

eventBus.post(event);
你可以在任意線程、任意位置發送事件,但要保證註冊與發送時用的是同一個 eventBus 對象。

處理時機

在註冊時那個 this 所屬的類中,編寫如下方法:

onEventMainThread(Event event):接到事件後,在主線程中消費事件。
onEvent(Event event):接到事件後,在 post 事件所在的線程中消費事件(注意不要做耗時操作,否則會阻塞事件傳遞)。
onEventBackgroundThread(Event event):在後台線程中消費事件。若 post 事件的線程本身就是後台線程,則沿用該線程,否則在新的子線程中消費。
onEventAsync(Event event):在新的子線程中消費事件。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved