編輯:關於 Android 程式設計
Otto 是 Square 推出的庫,位址:https://github.com/square/otto
官方描述是這樣的:An enhanced Guava-based event bus with emphasis on Android support. Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently. Forked from Guava, Otto adds unique functionality to an already refined event bus as well as specializing it to the Android platform.
簡單說,它是從 Guava 分支出來、針對 Android 強化的發布訂閱框架,用來讓應用中彼此不直接相依的元件之間能有效溝通。
public class AppConfig {
private static final Bus BUS = new Bus();
public static Bus getInstance() {
return BUS;
}
}
通常在 onCreate() 或 onResume() 中註冊:
AppConfig.getInstance().register(this);
@Subscribe
public void onWallpaperUpdate(MyObject obj) {
// 對 obj 做需要的處理
}
AppConfig.getInstance().post(myobj);
在 onDestroy() 或 onPause() 中解除,避免記憶體洩漏:
AppConfig.getInstance().unregister(this);
Otto 的原始碼非常精簡,所有類別都在 com.squareup.otto 一個套件中,不計內部類共 9 個:AnnotatedHandlerFinder(註解解析器)、Bus(總線核心)、DeadEvent(無接收者的事件)、EventHandler(事件訂閱者)、EventProducer(事件生產者)、HandlerFinder(取得生產者與訂閱者)、Produce(生產者註解)、Subscribe(訂閱者註解)、ThreadEnforcer(執行緒校驗)。
public Bus() { this(DEFAULT_IDENTIFIER); }
public Bus(String identifier) { this(ThreadEnforcer.MAIN, identifier); }
public Bus(ThreadEnforcer enforcer) { this(enforcer, DEFAULT_IDENTIFIER); }
public Bus(ThreadEnforcer enforcer, String identifier) {
this(enforcer, identifier, HandlerFinder.ANNOTATED);
}
Bus(ThreadEnforcer enforcer, String identifier, HandlerFinder handlerFinder) {
this.enforcer = enforcer;
this.identifier = identifier;
this.handlerFinder = handlerFinder;
}
一般都用無參數的 Bus(),並在整個 App 中維持單例。單例不只是省資源,更關乎正確性——若用 A 這個 Bus 註冊,卻用 B 去 post,訂閱方法永遠收不到訊息。
enforcer 負責執行緒校驗,有兩個取值:ThreadEnforcer.ANY 與 ThreadEnforcer.MAIN,預設是 MAIN,也就是預設建構出來的 Bus 只能在使用者主執行緒上呼叫。若在子執行緒註冊或發送,會直接拋出例外:
throw new IllegalStateException("Event bus " + bus
+ " accessed from non-main thread " + Looper.myLooper());
若確實需要跨執行緒,就傳入 ThreadEnforcer.ANY,或自行實作 ThreadEnforcer。只在主執行緒使用的好處是行為單純、不易出錯;但實務上跨執行緒溝通很常見,這點要特別留意。
identifier 只是一個識別字,用於 toString()。handlerFinder 負責解析註冊的物件,預設實作是 HandlerFinder.ANNOTATED,也就是走註解解析。
public void register(Object object) {
if (object == null) {
throw new NullPointerException("Object to register must not be null.");
}
enforcer.enforce(this);
Map<Class<?>, EventProducer> foundProducers = handlerFinder.findAllProducers(object);
for (Class<?> type : foundProducers.keySet()) {
final EventProducer producer = foundProducers.get(type);
EventProducer previousProducer = producersByType.putIfAbsent(type, producer);
if (previousProducer != null) {
throw new IllegalArgumentException("Producer method for type " + type
+ " found on type " + producer.target.getClass()
+ ", but already registered by type " + previousProducer.target.getClass() + ".");
}
Set<EventHandler> handlers = handlersByType.get(type);
if (handlers != null && !handlers.isEmpty()) {
for (EventHandler handler : handlers) {
dispatchProducerResultToHandler(handler, producer);
}
}
}
Map<Class<?>, Set<EventHandler>> foundHandlersMap = handlerFinder.findAllSubscribers(object);
for (Class<?> type : foundHandlersMap.keySet()) {
Set<EventHandler> handlers = handlersByType.get(type);
if (handlers == null) {
Set<EventHandler> handlersCreation = new CopyOnWriteArraySet<EventHandler>();
handlers = handlersByType.putIfAbsent(type, handlersCreation);
if (handlers == null) {
handlers = handlersCreation;
}
}
if (!handlers.addAll(foundHandlersMap.get(type))) {
throw new IllegalArgumentException("Object already registered.");
}
}
for (Map.Entry<Class<?>, Set<EventHandler>> entry : foundHandlersMap.entrySet()) {
Class<?> type = entry.getKey();
EventProducer producer = producersByType.get(type);
if (producer != null && producer.isValid()) {
for (EventHandler foundHandler : entry.getValue()) {
if (!producer.isValid()) break;
if (foundHandler.isValid()) {
dispatchProducerResultToHandler(foundHandler, producer);
}
}
}
}
}
流程是:先做非空檢查,再做執行緒校驗,接著解析出生產方法與訂閱方法。物件不可為 null,也不可重複註冊。
解析結果分別存在兩個屬性中:
private final ConcurrentMap<Class<?>, Set<EventHandler>> handlersByType
= new ConcurrentHashMap<Class<?>, Set<EventHandler>>();
private final ConcurrentMap<Class<?>, EventProducer> producersByType
= new ConcurrentHashMap<Class<?>, EventProducer>();
handlersByType 的 key 是訂閱方法的入參型別,value 是訂閱者物件與方法的集合;producersByType 的 key 是生產方法的回傳型別,value 是生產者物件與方法。
值得注意的一點:解析訂閱者時,若剛好存在對應的生產者,會自動呼叫生產方法,並立刻把結果派送給訂閱者一次。所謂「對應」,指的是 @Produce 方法的回傳型別與某個 @Subscribe 方法的參數型別相同。這段邏輯牽涉 register、dispatchProducerResultToHandler 與 dispatch 三個方法。
public void post(Object event) {
if (event == null) {
throw new NullPointerException("Event to post must not be null.");
}
enforcer.enforce(this);
Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass());
boolean dispatched = false;
for (Class<?> eventType : dispatchTypes) {
Set<EventHandler> wrappers = getHandlersForEventType(eventType);
if (wrappers != null && !wrappers.isEmpty()) {
dispatched = true;
for (EventHandler wrapper : wrappers) {
enqueueEvent(event, wrapper);
}
}
}
if (!dispatched && !(event instanceof DeadEvent)) {
post(new DeadEvent(this, event));
}
dispatchQueuedEvents();
}
這裡牽涉兩個 ThreadLocal:
private final ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>> eventsToDispatch
= new ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>>() {
@Override
protected ConcurrentLinkedQueue<EventWithHandler> initialValue() {
return new ConcurrentLinkedQueue<EventWithHandler>();
}
};
/** 當前執行緒是否正在派發事件 */
private final ThreadLocal<Boolean> isDispatching = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return false;
}
};
呼叫 post 之後,先做執行緒校驗,再依事件型別找出訂閱者。有訂閱者就把事件放進佇列;一個都沒有,就包成 DeadEvent 再 post 一次。DeadEvent 的註解寫得很清楚:Wraps an event that was posted, but which had no subscribers and thus could not be delivered. 訂閱 DeadEvent 對除錯與日誌記錄很有幫助,可以用來發現事件分發機制的配置錯誤。
接著 Bus 會從佇列中循環取件派送,概念上和 Android 的 Handler 訊息機制相似,只是這裡的循環在佇列取完後就結束:
protected void dispatchQueuedEvents() {
// 已在派發中就直接返回,避免重入導致事件順序錯亂;
// 剩下的事件留給進行中的派發處理完後再消費
if (isDispatching.get()) {
return;
}
isDispatching.set(true);
try {
while (true) {
EventWithHandler eventWithHandler = eventsToDispatch.get().poll();
if (eventWithHandler == null) {
break;
}
if (eventWithHandler.handler.isValid()) {
dispatch(eventWithHandler.event, eventWithHandler.handler);
}
}
} finally {
isDispatching.set(false);
}
}
佇列用 ThreadLocal 隔離,確保各執行緒互不干擾;同時多個執行緒可以各自跑自己的循環,派送效率自然更好。
public void unregister(Object object) {
if (object == null) {
throw new NullPointerException("Object to unregister must not be null.");
}
enforcer.enforce(this);
Map<Class<?>, EventProducer> producersInListener = handlerFinder.findAllProducers(object);
for (Map.Entry<Class<?>, EventProducer> entry : producersInListener.entrySet()) {
Class<?> key = entry.getKey();
EventProducer producer = getProducerForEventType(key);
EventProducer value = entry.getValue();
if (value == null || !value.equals(producer)) {
throw new IllegalArgumentException(
"Missing event producer for an annotated method. Is "
+ object.getClass() + " registered?");
}
producersByType.remove(key).invalidate();
}
}
與 register 對稱:非空檢查、執行緒校驗,然後清理。註冊與反註冊必須成對——沒註冊過不能反註冊,反註冊後也不能直接再反註冊一次。反註冊的重點是釋放參照、避免記憶體洩漏,之後該物件就不再收到相關訊息。
解析結果快取在兩個靜態 Map 中:
private static final ConcurrentMap<Class<?>, Map<Class<?>, Method>> PRODUCERS_CACHE
= new ConcurrentHashMap<Class<?>, Map<Class<?>, Method>>();
private static final ConcurrentMap<Class<?>, Map<Class<?>, Set<Method>>> SUBSCRIBERS_CACHE
= new ConcurrentHashMap<Class<?>, Map<Class<?>, Set<Method>>>();
結構相同:key 是被解析物件對應的 Class,value 以「型別 → 方法」的形式對應(生產者用回傳型別,訂閱者用參數型別)。
解析生產者的呼叫鏈是 findAllProducers → loadAnnotatedProducerMethods → loadAnnotatedMethods;解析訂閱者則是 findAllSubscribers → loadAnnotatedSubscriberMethods → loadAnnotatedMethods,最終都收斂到 loadAnnotatedMethods。
解析過程若違反規則會直接拋例外,這些規則值得背起來:
訂閱方法(@Subscribe)只能有一個參數;必須有具體實作,不能是介面;必須是 public。
生產方法(@Produce)必須無參數;回傳型別不能是 void;必須有具體實作,不能是介面;必須是 public;相同回傳型別的方法只能有一個。
Otto 非常輕量,實作大量依賴註解與反射,因此開啟混淆時要特別注意 keep 規則,否則容易出問題。
Android 上的事件總線選擇不算少:EventBus 相對重量級一些、功能更齊全,對執行緒的控制也更靈活;RxJava 同樣能勝任這件事;而最根本的觀察者模式,用原生的廣播或 Handler 機制其實也做得出來。最終還是回到專案需求,選一個團隊維護得起的方案即可。
Android 語音資料的即時擷取與播放:AudioRecord 與 AudioTrack
最近做的專案需要在單一地點即時擷取語音、送出,另一端即時接收並播放。這裡把核心程式碼記錄下來。 為什麼不用 MediaRecorder 多數 Android 開發者都知道
Android ListView 實現分類分隔欄效果(不用 ExpandableListView)
我們經常會遇到這樣的需求:一個 ListView 裡顯示的數據是有種類之分的。比如按春夏秋冬四季分組,每個季節下面再列出各自的條目;又比如通訊錄按 A、B、C 字母順序分
.NET 工程師轉戰 Android 開發(一):從零開始的環境建置
對沒碰過 Android 的人來說,第一印象往往是「門檻有點高」。但其實只要把環境準備好,後面的路就跟學任何一套新框架一樣:搞懂生命週期、搞懂資源管理、搞懂 UI 與資料
Android 自定義 ViewGroup(一)——帶箭頭的圓角矩形菜單
這次要做一个帶箭頭的圓角矩形菜單,大概是這個樣子: 要求:頂部的箭頭要對準菜單錨點,菜單項按壓時反色,背景色與按壓色可配置。 最偷工減料的做法是請 UX 切一張三角形圖