MessageQueue.cpp revision e6f43ddce78d6846af12550ff9193c5c6fe5844b
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdint.h>
18#include <errno.h>
19#include <sys/types.h>
20
21#include <utils/threads.h>
22#include <utils/Timers.h>
23#include <utils/Log.h>
24#include <binder/IPCThreadState.h>
25
26#include "MessageQueue.h"
27
28namespace android {
29
30// ---------------------------------------------------------------------------
31
32MessageBase::MessageBase()
33    : MessageHandler() {
34}
35
36MessageBase::~MessageBase() {
37}
38
39void MessageBase::handleMessage(const Message&) {
40    this->handler();
41    barrier.open();
42};
43
44// ---------------------------------------------------------------------------
45
46MessageQueue::MessageQueue()
47    : mLooper(new Looper(true)), mWorkPending(0)
48{
49}
50
51MessageQueue::~MessageQueue() {
52}
53
54void MessageQueue::waitMessage() {
55    do {
56        IPCThreadState::self()->flushCommands();
57
58        int32_t ret = mLooper->pollOnce(-1);
59        switch (ret) {
60            case ALOOPER_POLL_WAKE:
61            case ALOOPER_POLL_CALLBACK:
62                // callback and/or wake
63                if (android_atomic_and(0, &mWorkPending)) {
64                    return;
65                }
66                continue;
67
68            case ALOOPER_POLL_TIMEOUT:
69                // timeout (should not happen)
70                continue;
71
72            case ALOOPER_POLL_ERROR:
73                ALOGE("ALOOPER_POLL_ERROR");
74                continue;
75
76            default:
77                // should not happen
78                ALOGE("Looper::pollOnce() returned unknown status %d", ret);
79                continue;
80        }
81    } while (true);
82}
83
84status_t MessageQueue::postMessage(
85        const sp<MessageBase>& messageHandler, nsecs_t relTime)
86{
87    const Message dummyMessage;
88    if (relTime > 0) {
89        mLooper->sendMessageDelayed(relTime, messageHandler, dummyMessage);
90    } else {
91        mLooper->sendMessage(messageHandler, dummyMessage);
92    }
93    return NO_ERROR;
94}
95
96status_t MessageQueue::invalidate() {
97    if (android_atomic_or(1, &mWorkPending) == 0) {
98        mLooper->wake();
99    }
100    return NO_ERROR;
101}
102
103// ---------------------------------------------------------------------------
104
105}; // namespace android
106