Android通過AMessage進行消息傳遞,充滿了極其輕巧靈活的使用方式,讓人不得不稱贊
1)自發自用,發完不用管,最簡單場景
```
void MediaPuller::pause() {
? ? (new AMessage(kWhatPause, this))->post();
}
void MediaPuller::onMessageReceived(const sp<AMessage> &msg) {
? ? switch (msg->what()) {
? ? ? ? ? case kWhatPause:
? ? ? ? {
? ? ? ? ? ? mPaused = true;
? ? ? ? ? ? break;
? ? ? ? }
···
2)發送后需要等待響應
···
status_t MediaPuller::start() {
? ? return postSynchronouslyAndReturnError(new AMessage(kWhatStart, this));
}
調用msg->postAndAwaitResponse()該函數里面實際是個condition_wait(),發送方卡在這邊
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);? 實際是將發送方設置的tokern里reply message sp指向response; 然后broadcast signal 通知發送方就可以使用response消息了
? ? ? ? ? ? break;
···
3)消息里面帶消息,然后等事件處理完成后再通過消息觸發下一步操作
···
void WifiDisplaySource::PlaybackSession::Track::stopAsync() {
? ??sp<AMessage> msg = new AMessage(kWhatMediaPullerStopped, this);
? ?????????? mMediaPuller->stopAsync(msg);
void MediaPuller::stopAsync(const sp<AMessage> ¬ify) {
? ? sp<AMessage> msg = new AMessage(kWhatStop, this);
? ? msg->setMessage("notify", notify);
? ? msg->post();
}
void MediaPuller::stopAsync(const sp<AMessage> ¬ify) {
? ? 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:
? ? ? ? {//執行完響應后回復消息
? ??????????sp<AMessage> notify;
? ? ? ? ? ? CHECK(msg->findMessage("notify", ¬ify));
? ? ? ? ? ? notify->post();
? ? ? ? ? ? break;
? ? ? ? ?}
···
暫時先總結這3種, android的關于message的使用場景非常豐富,等看到后面奇妙的地方再分享