編輯:關於 Android 程式設計
在探討 Client 與 Server 之間如何通信之前,我們不妨先以 MediaServer 為例,看看一個普通 Server 進程在啟動之後究竟在做些什麼。
int main() {
……
// 獲得 ProcessState 實例
sp<ProcessState> proc(ProcessState::self());
// 得到 ServiceManager 的 Binder 客戶端實例
sp<IServiceManager> sm = defaultServiceManager();
……
// 通過 ServiceManager 的 Binder 客戶端向系統注冊 MediaPlayer 服務
MediaPlayerService::instantiate();
……
// 啟動線程池並進入消息循環
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
其中 defaultServiceManager() 在上一篇文章中已有介紹。MediaPlayerService::instantiate() 的實現如下,本質就是把服務 addService 到 ServiceManager,與上一篇講的 getService 類似,這裡不再贅述。
void MediaPlayerService::instantiate() {
defaultServiceManager()->addService(String16("media.player"), new MediaPlayerService());
}
接著看 ProcessState::self()->startThreadPool() 的實現:
void ProcessState::startThreadPool() {
AutoMutex _l(mLock);
if (!mThreadPoolStarted) {
mThreadPoolStarted = true;
spawnPooledThread(true);
}
}
void ProcessState::spawnPooledThread(bool isMain) {
if (mThreadPoolStarted) {
String8 name = makeBinderThreadName();
ALOGV("Spawning new pooled thread, name=%s\n", name.string());
sp<Thread> t = new PoolThread(isMain);
t->run(name.string());
}
}
class PoolThread : public Thread {
public:
PoolThread(bool isMain) : mIsMain(isMain) { }
protected:
virtual bool threadLoop() {
IPCThreadState::self()->joinThreadPool(mIsMain);
return false;
}
const bool mIsMain;
};
從代碼不難看出,這個函數做的事情其實很單純:創建一個新線程,然後在這個線程裡又構建了一個 IPCThreadState,並調用 joinThreadPool 函數。
void IPCThreadState::joinThreadPool(bool isMain) {
mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
set_sched_policy(mMyThreadId, SP_FOREGROUND);
status_t result;
do {
processPendingDerefs();
// 獲取下一条待處理的命令,若無則等待
result = getAndExecuteCommand();
if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting", mProcess->mDriverFD, result);
abort();
}
// 若不再需要且非主線程,則允許線程退出線程池
if (result == TIMED_OUT && !isMain) {
break;
}
} while (result != -ECONNREFUSED && result != -EBADF);
mOut.writeInt32(BC_EXIT_LOOPER);
talkWithDriver(false);
}
status_t IPCThreadState::getAndExecuteCommand() {
status_t result;
int32_t cmd;
result = talkWithDriver();
if (result >= NO_ERROR) {
size_t IN = mIn.dataAvail();
if (IN < sizeof(int32_t)) return result;
cmd = mIn.readInt32();
result = executeCommand(cmd);
set_sched_policy(mMyThreadId, SP_FOREGROUND);
}
return result;
}
由此可見,無論是主線程還是新創建的線程,本質上都在重復同一件事:通過 talkWithDriver 讀取 Binder 驅動,再交由 executeCommand 處理請求。這正是普通 Server 進程啟動之後一直維持的狀態——等待客戶端請求、處理請求,然後把結果返回給客戶端。
Server 進程準備就緒之後,接下來就該轮到 Client 端登場了。Client 將通過 Binder 向 Server 發起請求,讓它完成某些工作。先看代碼:
status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length) {
status_t err = UNKNOWN_ERROR;
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(fd, offset, length))) {
player.clear();
}
err = attachNewPlayer(player);
}
return err;
}
getMediaPlayerService() 之前分析過,它會返回一個 BpMediaPlayerService。這裡有一個值得思考的問題:為什麼這個 BpMediaPlayerService 能夠與 MediaPlayerService 進程進行 Binder 通信,而不是與其他 Server 進程通信呢?
我們再回顧一下相關代碼:
/*static*/const sp<IMediaPlayerService>& IMediaDeathNotifier::getMediaPlayerService() {
Mutex::Autolock _l(sServiceLock);
if (sMediaPlayerService == 0) {
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder;
do {
binder = sm->getService(String16("media.player"));
if (binder != 0) {
break;
}
ALOGW("Media player service not published, waiting...");
usleep(500000); // 0.5 s
} while (true);
if (sDeathNotifier == NULL) {
sDeathNotifier = new DeathNotifier();
}
binder->linkToDeath(sDeathNotifier);
sMediaPlayerService = interface_cast<IMediaPlayerService>(binder);
}
ALOGE_IF(sMediaPlayerService == 0, "no media player service!?");
return sMediaPlayerService;
}
答案其實就藏在 binder = sm->getService(String16("media.player")) 這一句裡,返回的 binder 將作為 BpMediaPlayerService 構造函數的參數。下面我們來看 getService 的實現:
virtual sp<IBinder> getService(const String16& name) const {
unsigned n;
for (n = 0; n < 5; n++){
sp<IBinder> svc = checkService(name);
if (svc != NULL) return svc;
ALOGI("Waiting for service %s...\n", String8(name).string());
sleep(1);
}
return NULL;
}
virtual sp<IBinder> checkService(const String16& name) const {
Parcel data, reply;
data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
data.writeString16(name);
remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply);
return reply.readStrongBinder();
}
sp<IBinder> Parcel::readStrongBinder() const {
sp<IBinder> val;
unflatten_binder(ProcessState::self(), *this, &val);
return val;
}
status_t unflatten_binder(const sp<ProcessState>& proc, const Parcel& in, sp<IBinder>* out) {
const flat_binder_object* flat = in.readObject(false);
if (flat) {
switch (flat->type) {
case BINDER_TYPE_BINDER:
*out = static_cast<IBinder*>(flat->cookie);
return finish_unflatten_binder(NULL, *flat, in);
case BINDER_TYPE_HANDLE:
*out = proc->getStrongProxyForHandle(flat->handle);
return finish_unflatten_binder(static_cast<BpBinder*>(out->get()), *flat, in);
}
}
return BAD_TYPE;
}
在 unflatten_binder 函數中,flat->type 與 flat->handle 的值是在 ServiceManager 中被賦值的:flat->type 的值為 BINDER_TYPE_HANDLE,而 flat->handle 的值則是所查詢 Service 對應的 Handle 值。中間過程涉及 Binder 底層驅動的代碼,這裡暫不展開。
因此,當 binder = sm->getService(String16("media.player")) 執行完成後,binder 就等於 BpBinder(Handle),其中 Handle 的值為所查詢 Service 對應的 Handle。至此,Client 端與 Service 端之間的通信通路便建立起來了。
分析完 getMediaPlayerService()、建立起通信通路之後,接下來就正式進入通信環節。
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
我們進入 IMediaPlayerService.cpp 看看 create 的實現:
virtual sp<IMediaPlayer> create(const sp<IMediaPlayerClient>& client, int audioSessionId) {
Parcel data, reply;
data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor());
data.writeStrongBinder(client->asBinder());
data.writeInt32(audioSessionId);
remote()->transact(CREATE, data, &reply);
return interface_cast<IMediaPlayer>(reply.readStrongBinder());
}
經過前面的分析,我們很容易就能理解:remote() 返回的是 BpBinder(handle),而 transact(CREATE, data, &reply) 會把數據寫入 Binder 驅動並喚醒 Service 進程。接下來我們看看 Server 端會作何反應。既然已知 Server 進程一直在讀取 Binder 驅動並執行 executeCommand,那就直接看 executeCommand 的實現:
status_t IPCThreadState::executeCommand(int32_t cmd) {
BBinder* obj;
RefBase::weakref_type* refs;
status_t result = NO_ERROR;
switch (cmd) {
……
case BR_TRANSACTION: {
binder_transaction_data tr;
result = mIn.read(&tr, sizeof(tr));
ALOG_ASSERT(result == NO_ERROR, "Not enough command data for brTRANSACTION");
if (result != NO_ERROR) break;
Parcel buffer;
buffer.ipcSetDataReference(
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(size_t), freeBuffer, this);
const pid_t origPid = mCallingPid;
const uid_t origUid = mCallingUid;
mCallingPid = tr.sender_pid;
mCallingUid = tr.sender_euid;
int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
// ...(優先級處理邏輯略)
Parcel reply;
if (tr.target.ptr) {
sp<BBinder> b((BBinder*)tr.cookie);
const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);
if (error < NO_ERROR) reply.setError(error);
} else {
const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
if (error < NO_ERROR) reply.setError(error);
}
if ((tr.flags & TF_ONE_WAY) == 0) {
LOG_ONEWAY("Sending reply to %d!", mCallingPid);
sendReply(reply, 0);
} else {
LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
}
mCallingPid = origPid;
mCallingUid = origUid;
}
break;
……
default:
printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
result = UNKNOWN_ERROR;
break;
}
if (result != NO_ERROR) {
mLastError = result;
}
return result;
}
請重點關注這一段:
if (tr.target.ptr) {
sp<BBinder> b((BBinder*)tr.cookie);
const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);
if (error < NO_ERROR) reply.setError(error);
} else {
const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
if (error < NO_ERROR) reply.setError(error);
}
這裡的 b 實際上就是我們在 addService 時創建的 MediaPlayerService 對象,它經過包括 Binder 驅動在內的傳輸與轉換,最終變成了這樣一個數據類型。
void MediaPlayerService::instantiate() {
defaultServiceManager()->addService(String16("media.player"), new MediaPlayerService());
}
再看下面的繼承關系:
class MediaPlayerService : public BnMediaPlayerService
由於 MediaPlayerService 本身並沒有實現 transact 方法,因此 b->transact(tr.code, buffer, &reply, tr.flags) 實際調用的是 BnMediaPlayerService 的 transact 方法。
進入 IMediaPlayerService.cpp 找到 BnMediaPlayerService 的 onTransact 方法,如下:
status_t BnMediaPlayerService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
switch (code) {
case CREATE: {
CHECK_INTERFACE(IMediaPlayerService, data, reply);
sp<IMediaPlayerClient> client = interface_cast<IMediaPlayerClient>(data.readStrongBinder());
int audioSessionId = data.readInt32();
sp<IMediaPlayer> player = create(client, audioSessionId);
reply->writeStrongBinder(player->asBinder());
return NO_ERROR;
}
break;
……
}
其中 sp<IMediaPlayer> player = create(client, audioSessionId) 調用的 create 方法在 MediaPlayerService 類中實現,進入 MediaPlayerService.cpp:
sp<IMediaPlayer> MediaPlayerService::create(const sp<IMediaPlayerClient>& client, int audioSessionId) {
pid_t pid = IPCThreadState::self()->getCallingPid();
int32_t connId = android_atomic_inc(&mNextConnId);
sp<Client> c = new Client(this, pid, connId, client, audioSessionId,
IPCThreadState::self()->getCallingUid());
ALOGV("Create new client(%d) from pid %d, uid %d, ", connId, pid,
IPCThreadState::self()->getCallingUid());
c->setScreen(mScreen);
c->setSubGate(mGlobalSubGate);
wp<Client> w = c;
{
Mutex::Autolock lock(mLock);
mClients.add(w);
}
return c;
}
至此,Server 已經處理完畢,接下來把結果返回給 Client,關鍵代碼如下:
if ((tr.flags & TF_ONE_WAY) == 0) {
LOG_ONEWAY("Sending reply to %d!", mCallingPid);
sendReply(reply, 0);
} else {
LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
}
status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags) {
status_t err;
status_t statusBuffer;
err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
if (err < NO_ERROR) return err;
return waitForResponse(NULL, NULL);
}
可以看到,調用 sendReply 會把結果寫回 Binder 驅動,從而得以返回給 Client 進程。至此,一次完整的通信便圓滿完成。
Android ListView 分組與懸浮 Header 實作方法
分組清單與懸浮標題是常見的資訊呈現方式。Android 原生 ListView 沒有直接提供這種效果,但可透過自訂 Adapter 與 Header View 模擬。
Android ListView 圓角效果實作解析
在介面設計中,直角與圓角各有適用場景。相較於稜角分明的列表,圓角設計通常更柔和,也更容易營造輕鬆活潑的視覺感受。本文示範如何為 Android 的 ListView 加上
Android pullToRefresh 下拉刷新庫的導入與使用心得
pullToRefresh 的導入首先點擊 New 按鈕,選擇 Import Module。接著在 New Module 介面中,選擇本機已含源碼的 pullToRefr
Android Service 與 AIDL 通信實戰:來電狀態監聽示例
本文以一個「來電狀態監聽」的技術演示為例,帶大家理解 Android 中幾個重點知識:如何通過 Service 在後台持續運行、如何借助 PhoneStateListen