編輯:關於 Android 程式設計
EventBus 想解決的是一個很日常的痛:回呼太多。A 函式做完之後要呼叫 B 類的 C 函式,傳統做法是定義一個介面,在 A 所屬的類裡註冊實作,A 做完直接呼叫介面。這種模式寫一兩次還好,寫多了確實很煩。EventBus 就是為了解掉這個場景而生。
一如往常,這裡只讀源碼,用法請自行參考官方文件。
private synchronized void register(Object subscriber, boolean sticky, int priority) {
// 這個 list 就是方法的集合
List<SubscriberMethod> subscriberMethods =
subscriberMethodFinder.findSubscriberMethods(subscriber.getClass());
// 用「方法物件」組出 Subscription
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}
final class SubscriberMethod {
final Method method;
final ThreadMode threadMode;
final Class<?> eventType;
String methodString; // 用於高效比較
SubscriberMethod(Method method, ThreadMode threadMode, Class<?> eventType) {
this.method = method;
this.threadMode = threadMode;
this.eventType = eventType;
}
@Override
public boolean equals(Object other) {
if (other instanceof SubscriberMethod) {
checkMethodString();
SubscriberMethod otherSubscriberMethod = (SubscriberMethod) other;
otherSubscriberMethod.checkMethodString();
// 不用 method.equals,因為
// https://code.google.com/p/android/issues/detail?id=7811#c6
return methodString.equals(otherSubscriberMethod.methodString);
}
return false;
}
private synchronized void checkMethodString() {
if (methodString == null) {
StringBuilder builder = new StringBuilder(64);
builder.append(method.getDeclaringClass().getName());
builder.append('#').append(method.getName());
builder.append('(').append(eventType.getName());
methodString = builder.toString();
}
}
@Override
public int hashCode() {
return method.hashCode();
}
}
methodString 的樣子像這樣:com.example.ItemDetailFragment#onEventMainThread(com.example.Item),也就是「套件名 + 類名 # 方法名(參數型別)」。它存在的目的很單純——在 equals 中做快速比較,而刻意不用 Method.equals 是為了繞開 Android 上的一個已知 bug。
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
String key = subscriberClass.getName();
List<SubscriberMethod> subscriberMethods;
synchronized (methodCache) {
subscriberMethods = methodCache.get(key);
}
if (subscriberMethods != null) {
return subscriberMethods; // 命中快取
}
subscriberMethods = new ArrayList<SubscriberMethod>();
Class<?> clazz = subscriberClass;
HashSet<String> eventTypesFound = new HashSet<String>();
StringBuilder methodKeyBuilder = new StringBuilder();
while (clazz != null) {
String name = clazz.getName();
// 遇到 java. / javax. / android. 開頭就停止,
// 過濾掉 SDK 基礎類別
if (name.startsWith("java.") || name.startsWith("javax.")
|| name.startsWith("android.")) {
break;
}
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
// 只有以 onEvent 開頭的方法才是我們要的
if (methodName.startsWith(ON_EVENT_METHOD_NAME)) {
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0
&& (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
String modifierString =
methodName.substring(ON_EVENT_METHOD_NAME.length());
ThreadMode threadMode;
if (modifierString.length() == 0) {
threadMode = ThreadMode.PostThread;
} else if (modifierString.equals("MainThread")) {
threadMode = ThreadMode.MainThread;
} else if (modifierString.equals("BackgroundThread")) {
threadMode = ThreadMode.BackgroundThread;
} else if (modifierString.equals("Async")) {
threadMode = ThreadMode.Async;
} else {
throw new EventBusException(
"Illegal onEvent method, check for typos: " + method);
}
Class<?> eventType = parameterTypes[0];
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(methodName);
methodKeyBuilder.append('>').append(eventType.getName());
// 例如 onEventMainThread>java.lang.String
String methodKey = methodKeyBuilder.toString();
// 若 add 成功才建立,避免子類重複
if (eventTypesFound.add(methodKey)) {
subscriberMethods.add(
new SubscriberMethod(method, threadMode, eventType));
}
}
}
}
}
clazz = clazz.getSuperclass(); // 繼續往父類找
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " has no public methods called " + ON_EVENT_METHOD_NAME);
} else {
synchronized (methodCache) {
methodCache.put(key, subscriberMethods);
}
return subscriberMethods;
}
}
幾個值得注意的设计:
onEvent 後面的後綴推斷 ThreadMode,寫錯字串就丟 EventBusException,把錯誤提早到註冊階段而非執行期。eventTypesFound.add(methodKey) 的去重技巧:子類覆寫父類的同名方法時,只保留一份。private void subscribe(Object subscriber, SubscriberMethod subscriberMethod,
boolean sticky, int priority) {
Class<?> eventType = subscriberMethod.eventType;
CopyOnWriteArrayList<Subscription> subscriptions =
subscriptionsByEventType.get(eventType);
Subscription newSubscription =
new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<Subscription>();
subscriptionsByEventType.put(eventType, subscriptions);
} else if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass()
+ " already registered to event " + eventType);
}
// 優先級高的排在前面
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
subscriptions.add(i, newSubscription);
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<Class<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (sticky) {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
這裡的資料結構是理解 EventBus 的關鍵:
/** key 是 eventType,value 是該事件對應的方法清單 */
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
Subscription 則把三件事綁在一起:
final class Subscription {
final Object subscriber; // 方法所屬的物件
final SubscriberMethod subscriberMethod; // 對方法的描述
final int priority; // 優先級
volatile boolean active;
}
所以三者关系是:SubscriberMethod 描述「哪個方法」,Subscription = SubscriberMethod + 所屬物件 + 優先級。register 的整體流程就是:先掃出需要的方法 → 組 List → 逐一包裝成 Subscription → 存進 subscriptionsByEventType(key 是事件型別,value 是方法清單)。
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
// isPosting 保證同一時間只有一個執行緒在處理括號內的內容;
// currentPostingThreadState 由 ThreadLocal 建構,天然具備同步性
if (!postingState.isPosting) {
postingState.isMainThread =
Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
try {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
PostingThreadState 是靜態內部類,裡頭除了一個佇列,還有幾個狀態位:
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
這個設計很聰明:同一執行緒連續呼叫多次 post,事件會累積在同一個佇列裡一次處理完,不必每次都走一輪 while 迴圈。而 ThreadLocal 保證不同執行緒各有自己的佇列與狀態。
private void postSingleEvent(Object event, PostingThreadState postingState) {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
for (int h = 0; h < eventTypes.size(); h++) {
subscriptionFound |= postSingleEventForEventType(
event, postingState, eventTypes.get(h));
}
} else {
subscriptionFound = postSingleEventForEventType(
event, postingState, eventClass);
}
if (!subscriptionFound && sendNoSubscriberEvent
&& eventClass != NoSubscriberEvent.class
&& eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
private boolean postSingleEventForEventType(Object event,
PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
return true;
}
return false;
}
就是從註冊階段存好的 Map 裡把方法取出來,準備反射呼叫。eventInheritance 開啟時,事件還會沿著型別繼承鏈往上找訂閱者,所以訂閱父類別就能收到所有子類事件。
private void postToSubscription(Subscription subscription, Object event,
boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case PostThread:
invokeSubscriber(subscription, event);
break;
case MainThread:
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case BackgroundThread:
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
invokeSubscriber(subscription, event);
}
break;
case Async:
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException(
"Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
四種模式的意圖一目了然:
HandlerPoster。BackgroundPoster。AsyncPoster,走執行緒池。// 初始化
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
final class HandlerPoster extends Handler {
private final PendingPostQueue queue;
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.eventBus = eventBus;
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
queue = new PendingPostQueue();
}
void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
pendingPost = queue.poll(); // 同步區內再確認一次
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
// 單次 handleMessage 停留太久,就重新排隊讓下一篇訊息有機會執行
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
sendMessage(obtainMessage());
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
}
maxMillisInsideHandleMessage(這裡是 10ms)是個細膩的設計:一次 handleMessage 最多處理 10 毫秒就主動讓出,避免大量事件把主執行緒的訊息佇列堵死,導致 UI 無法回應。
final class BackgroundPoster implements Runnable {
private final PendingPostQueue queue;
private final EventBus eventBus;
private volatile boolean executorRunning;
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
eventBus.getExecutorService().execute(this);
}
}
}
@Override
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName()
+ " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
}
它是 Runnable,跑在子執行緒,一次只處理一個事件,串行執行。這點很重要:BackgroundThread 模式的語意是「不要在主執行緒做」,而不是「併發做」。
class AsyncPoster implements Runnable {
private final PendingPostQueue queue;
private final EventBus eventBus;
AsyncPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
}
和 BackgroundPoster 一樣在子執行緒,但每次 enqueue 都直接丟進執行緒池,因此可以多任務併發——這正是兩者的分野,也是選擇 ThreadMode 時最該想清楚的一點。
EventBus 表面上是「事件總線」,骨子裡是三件事的組合:用反射掃描 + 方法快取完成註冊,用 ThreadLocal + 佇列完成事件遞送,用四種 Poster把執行緒策略外置成一個可宣告的屬性。理解這三層之後,不難在自己的專案裡模仿出同樣的設計——這大概就是讀源碼最大的價值。
Android 錄音與播放功能的簡單實例
錄音與播放是 Android 多媒體開發中的基礎功能。透過 MediaRecorder 可以錄製音頻,透過 MediaPlayer 則可以播放錄音檔案。兩者搭配,就能完成
Android 數據存儲之外部存儲(SD 卡)External Storage 完全指南
一、特點1、需要插入 SD 卡;2、分為兩部分:SD 的公共目錄與 SD 的私有目錄;3、公共目錄下的文件可被各應用程序共享,私有目錄下的文件僅能被當前應用訪問;4、程序
Android 簡單實作 ListView 頂部懸浮效果
先看成果: 這種效果在聯絡人、應用列表這類介面上很常見:捲動時,目前分組的標題會吸附在頂部;進入下一分組時,舊標題被往上推走,新標題接手。以下示範最簡單的實作。 核心思
Android 開發入門必備:Log 日誌全解析(Log.v / Log.d / Log.i / Log.w / Log.e)
在不少 Android 學習社群裡,總有人好奇 Log 到底該怎麼用。今天我把網路上與 SDK 文件裡整理出來的心得一次分享給大家,希望對剛入門的朋友有實質的幫助。 an