輕巧如燕的AMessage

Android通過AMessage進行消息傳遞,充滿了極其輕巧靈活的使用方式,讓人不得不稱贊

1)自發(fā)自用,發(fā)完不用管,最簡單場景

```

void MediaPuller::pause() {

? ? (new AMessage(kWhatPause, this))->post();

}

void MediaPuller::onMessageReceived(const sp<AMessage> &msg) {

? ? switch (msg->what()) {

? ? ? ? ? case kWhatPause:

? ? ? ? {

? ? ? ? ? ? mPaused = true;

? ? ? ? ? ? break;

? ? ? ? }

···

2)發(fā)送后需要等待響應

···

status_t MediaPuller::start() {

? ? return postSynchronouslyAndReturnError(new AMessage(kWhatStart, this));

}

調(diào)用msg->postAndAwaitResponse()該函數(shù)里面實際是個condition_wait(),發(fā)送方卡在這邊

status_t MediaPuller::postSynchronouslyAndReturnError(

? ? ? ? const sp<AMessage> &msg) {

? ? sp<AMessage> response;

? ? status_t err = msg->postAndAwaitResponse(&response);

? ? if (err != OK) {

? ? ? ? return err;

? ? }

? ? if (!response->findInt32("err", &err)) {

? ? ? ? err = OK;

? ? }

? ? return err;

}

接收方

void MediaPuller::onMessageReceived(const sp<AMessage> &msg) {

? ? switch (msg->what()) {

? ? ? ? case kWhatStart:

? ? ? ? {

? ? ? ? ? ?.......

? ? ? ? ? ? sp<AMessage> response = new AMessage;

? ? ? ? ? ? response->setInt32("err", err);

? ? ? ? ? ? sp<AReplyToken> replyID;

? ? ? ? ? ? CHECK(msg->senderAwaitsResponse(&replyID)); //查看msg是否設置過replyToken,設置過才需要回復

? ? ? ? ? ? response->postReply(replyID); //looper->postReply(replyToken, this);? 實際是將發(fā)送方設置的tokern里reply message sp指向response; 然后broadcast signal 通知發(fā)送方就可以使用response消息了

? ? ? ? ? ? break;

···

3)消息里面帶消息,然后等事件處理完成后再通過消息觸發(fā)下一步操作

···

void WifiDisplaySource::PlaybackSession::Track::stopAsync() {

? ??sp<AMessage> msg = new AMessage(kWhatMediaPullerStopped, this);

? ?????????? mMediaPuller->stopAsync(msg);

void MediaPuller::stopAsync(const sp<AMessage> &notify) {

? ? sp<AMessage> msg = new AMessage(kWhatStop, this);

? ? msg->setMessage("notify", notify);

? ? msg->post();

}

void MediaPuller::stopAsync(const sp<AMessage> &notify) {

? ? sp<AMessage> msg = new AMessage(kWhatStop, this);

? ? msg->setMessage("notify", notify);

? ? msg->post();

}

void MediaPuller::onMessageReceived(const sp<AMessage> &msg) {

? ? switch (msg->what()) {? ?

? ? ? ? case kWhatStop:

? ? ? ? {//執(zhí)行完響應后回復消息

? ??????????sp<AMessage> notify;

? ? ? ? ? ? CHECK(msg->findMessage("notify", &notify));

? ? ? ? ? ? notify->post();

? ? ? ? ? ? break;

? ? ? ? ?}

···

暫時先總結(jié)這3種, android的關于message的使用場景非常豐富,等看到后面奇妙的地方再分享

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容