今天, 我們來看看AHandle的聲明以及定義.
首先, 先來看看頭文件是如何聲明的(關鍵方法, 已附上簡要說明):
聲明
#ifndef A_HANDLER_H_
#define A_HANDLER_H_
#include <media/stagefright/foundation/ALooper.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
namespace android {
struct AMessage;
struct AHandler : public RefBase {
AHandler()
: mID(0),
mVerboseStats(false),
mMessageCounter(0) {
}
//獲取本handler的ID號(唯一)
ALooper::handler_id id() const {
return mID;
}
sp<ALooper> looper() const {
return mLooper.promote();
}
//獲取本handler注冊其中的Looper
wp<ALooper> getLooper() const {
return mLooper;
}
wp<AHandler> getHandler() const {
// allow getting a weak reference to a const handler
return const_cast<AHandler *>(this);
}
protected:
//純虛函數(shù), 具體的實現(xiàn), 在Nuplayer結構中, 由各個繼承于AHandler的類來實現(xiàn)
virtual void onMessageReceived(const sp<AMessage> &msg) = 0;
private:
friend struct AMessage; // deliverMessage()
friend struct ALooperRoster; // setID()
ALooper::handler_id mID;
wp<ALooper> mLooper;
//***重要***: 將本handler注冊到指定的Looper當中
inline void setID(ALooper::handler_id id, wp<ALooper> looper)
{
mID = id;
mLooper = looper;
}
bool mVerboseStats;
uint32_t mMessageCounter;
KeyedVector<uint32_t, uint32_t> mMessages;
//顧名思義, 交付消息
void deliverMessage(const sp<AMessage> &msg);
DISALLOW_EVIL_CONSTRUCTORS(AHandler);
};
} // namespace android
#endif // A_HANDLER_H_
可以看到, AHandler并不復雜, 現(xiàn)在來看看關鍵方法具體是如何實現(xiàn)功能的.
定義
#define LOG_TAG "AHandler"
#include <utils/Log.h>
#include <media/stagefright/foundation/AHandler.h>
#include <media/stagefright/foundation/AMessage.h>
namespace android {
void AHandler::deliverMessage(const sp<AMessage> &msg) {
onMessageReceived(msg);
mMessageCounter++;
if (mVerboseStats) {
uint32_t what = msg->what();
ssize_t idx = mMessages.indexOfKey(what);
if (idx < 0) {
mMessages.add(what, 1);
} else {
mMessages.editValueAt(idx)++;
}
}
}
各位童鞋可能要吐瓜子了, 神馬鬼, 就這一個AHandler::deliverMessage
???
答: 確實就這一個方法咯
簡要分析下:
-
onMessageReceived(msg);
把要交付的消息給到onMessageReceived
處理; - 增加交付了的消息的計數(shù);
- 如果是設置了
mVerboseStats
.
- 把設置的what(AMessage中會看到, 這里只需要知道是發(fā)送消息的標識, AHandler會通過這個標識, 在onMessageReceived中尋找對應的方法來處理)
mMessages
是在頭文件定義的. 它長這個樣子KeyedVector<uint32_t, uint32_t> mMessages;
. 哦, 原來它是個鍵值對. 在ssize_t idx = mMessages.indexOfKey(what);
中 獲取到了idx(其實就是計數(shù)).- 最后, 判斷下. 如果這個計數(shù)中的what未被交付過, 設置為1; 否則, idx計數(shù)加一.
小結
AHandler中重要的是在onMessageReceived
處理邏輯中, 而在此只是聲明了一個純虛函數(shù), 在今后分析Nuplayer框架的時候, 各位童鞋們就能看到其中的奧妙了.