轻巧如燕的AMessage

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> &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:

        {//执行完响应后回复消息

            sp<AMessage> notify;

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

            notify->post();

            break;

         }

···

暂时先总结这3种, android的关于message的使用场景非常丰富,等看到后面奇妙的地方再分享

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容