Android Looper类代码分析

来源:互联网 发布:windows xp outlook 编辑:程序博客网 时间:2024/05/29 15:56

本文将分析一下Looper类的实现及其应用,代码位于

frameworks/native/lib/utils/Looper.cpp。主要分为如下几个部分:

1. epoll系统调用接口简介

2. Looper类代码分析

3. Looper类应用实例分析


一、epoll系统调用接口简介

Looper事件机制实际上是依赖系统调用epoll实现的。它是一种I/O复用模型,即可以同时监控多个I/O事件。对于Looper来说,所谓的I/O事件就是所监控的文件描述符上没有有数据到达。epoll的主要接口如下所示 :

1. epoll_create():创建一个epoll实例,返回引用该实例的文件描述符。

原型如下所示 :

 

int epoll_create(int size );

 

参数size指定了我们想通过epoll实例监控文件描述符的数量。

 

2. epoll_ctl():操作与该epoll实例相关联的兴趣列表:添加一个文件描述符到兴趣列表中,从兴趣列表中删除一个现存的文件描述符以及修改事件掩码以决定要监控文件描述符上发生的哪个事件。

原型如下所示:

 

int epoll_ctl(int epfd , int op , int fd , struct epoll_event * ev );

 

其中参数op可以取如下一些值:

 

EPOLL_CTL_ADD

fd加入了监控列表

EPOLL_CTL_MOD

修改当前监控的fd相关信息

EPOLL_CTL_DEL

fd从监控列表中删除

 

 

3. epoll_wait():从I/O Ready列表中返回与epoll实例相关联的项,即返回有事件发生的文件描述符的数量。

      原型如下所示:

 

int epoll_wait(int epfd , struct epoll_event * evlist , int maxevents , int timeout );

 

其中timeout值为-1时,表示无限等待直到有事件发生。为0时,执行一个非阻塞检查后立即返回。大于0时,表示一个超时时间值。

另外,struct epoll_event结构定义如下所示 :

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. struct epoll_event {  
  2.     uint32_t events;  /* epoll events (bit mask) */  
  3.     epoll_data_t data; /* User data */  
  4. };  

主要的事件掩码有:

EPOLLIN:代表有数据可读

EPOLLOUT:代表有数据可写

 

epoll_data_t的数据结构定义如下:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. typedef union epoll_data {  
  2.     void *ptr;  /* Pointer to user-defined data */  
  3.     int fd;  /*File descriptor */  
  4.     uint32_t u32; /* 32-bit integer */  
  5.     uint64_t u64; /* 64-bit integer */  
  6. } epoll_data_t;  

使用实例:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. int epfd;  
  2. struct epoll_event ev;  
  3. epfd = epoll_create(5);  
  4. if (epfd == -1)  
  5.     errExit("epoll_create");  
  6. ev.data.fd = fd;  
  7. ev.events = EPOLLIN;  
  8. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, ev) == -1)  
  9.     errExit("epoll_ctl");  
  10. ...  
  11. epoll_wait(...);  

二、Looper类代码分析

Looper类定义了一种事件接口,这里所谓的事件就是文件描述符上的I/O数据是否可读或可写。它提供了一系列接口来支持事件通知和响应,通过轮询,利用epoll系统调用,可以侦测到发生在文件描述符上的I/O事件。

在分析Looper类之前,我们先来看两个与之相关的接口:

1. Looper消息处理接口。

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. class MessageHandler : public virtual RefBase {  
  2. protected:  
  3.     virtual ~MessageHandler() { }  
  4.   
  5. public:  
  6.     /** 
  7.      * Handles a message. 
  8.      */  
  9.     virtual void handleMessage(const Message& message) = 0;  
  10. };  

与之相关的Looper类的几个成员函数定义如下:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * Enqueues a message to be processed by the specified handler. 
  3.      */  
  4.     void sendMessage(const sp<MessageHandler>& handler, const Message& message);  
  5.   
  6.     /** 
  7.      * Enqueues a message to be processed by the specified handler after all pending messages 
  8.      * after the specified delay. 
  9.      */  
  10.     void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,  
  11.             const Message& message);  
  12.   
  13.     /** 
  14.      * Enqueues a message to be processed by the specified handler after all pending messages 
  15.      * at the specified time. 
  16.      */  
  17.     void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,  
  18.             const Message& message);  
  19.   
  20.     /** 
  21.      * Removes all messages for the specified handler from the queue. 
  22.      */  
  23.     void removeMessages(const sp<MessageHandler>& handler);  
  24.   
  25.     /** 
  26.      * Removes all messages of a particular type for the specified handler from the queue. 
  27.      */  
  28.     void removeMessages(const sp<MessageHandler>& handler, int what);  

从上述成员函数的定义可以看到,LooperMessageHandler都拥有强引用,所以需要通过显式调用remoeveMessage将其删掉。

此外,也定义了一个WeakMessageHandler类,它通过一个弱引用来引用一个MessageHandler对象,在需要的时候强化为强引用。

1. Looper回调函数接口。

回调函数类定义如下:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * A looper callback. 
  3.  */  
  4. class LooperCallback : public virtual RefBase {  
  5. protected:  
  6.     virtual ~LooperCallback() { }  
  7.   
  8. public:  
  9.     /** 
  10.      * Handles a poll event for the given file descriptor. 
  11.      * It is given the file descriptor it is associated with, 
  12.      * a bitmask of the poll events that were triggered (typically ALOOPER_EVENT_INPUT), 
  13.      * and the data pointer that was originally supplied. 
  14.      * 
  15.      * Implementations should return 1 to continue receiving callbacks, or 0 
  16.      * to have this file descriptor and callback unregistered from the looper. 
  17.      */  
  18.     virtual int handleEvent(int fd, int events, void* data) = 0;  
  19. };  

同样地,也定义了一个辅助类SimpleLooperCallback,它支持接受一个回调函数指针。

typedef int (*ALooper_callbackFunc)(int fd, int events, void* data);

与之相关的Looper类的成员函数如下所示 :

    int addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data);

    int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);

这两个成员函数的主要作用是:将要监控的fd加入到Looper的事件监控列表中。这里,可以指定回调函数。当有事件发生时,Looper实例会自动调用回调函数。如果回调函数为空,则由调用者处理发生的事件。

 

下面将分析Looper类的实现。

先分析下成员变量的意义:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. const bool mAllowNonCallbacks; // immutable  
  2.   
  3.   int mWakeReadPipeFd;  // immutable  
  4.   int mWakeWritePipeFd; // immutable  
  5.   Mutex mLock;  
  6.   
  7.   Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock  
  8.   bool mSendingMessage; // guarded by mLock  
  9.   
  10.   int mEpollFd; // immutable  
  11.   
  12.   // Locked list of file descriptor monitoring requests.  
  13.   KeyedVector<int, Request> mRequests;  // guarded by mLock  
  14.   
  15.   // This state is only used privately by pollOnce and does not require a lock since  
  16.   // it runs on a single thread.  
  17.   Vector<Response> mResponses;  
  18.   size_t mResponseIndex;  
  19.   nsecs_t mNextMessageUptime; // set to LLONG_MAX when none  

它们的表示的意义如下所示:

mAllowNonCallbacks: 表示是否允许将文件描述符加入监控对象时,指定回调函数为空。

mWakeReadPipeFd:Looper类默认构造的双向管道的只读端。

mWakeWritePipeFd:Looper类默认构造的双向管道的只写端。

mLock:互斥访问保护锁,主要Looper类的一些成员变量的并发访问。

mMessageEnvelopes:Looper实例包含的消息信封集合。消息信封主要包含如下属性:

时间戳,消息处理函数指针以及消息本身。

mSendingMessage:当前Looper实例是否正在发送消息。

mEpollFd:epoll实例对应的描述符。

mRequests:当前Looper实例中的文件描述符监控请求。对就的数据结构struct Request定义如下:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. struct Request {  
  2.        int fd;  
  3.        int ident;  
  4.        sp<LooperCallback> callback;  
  5.        void* data;  
  6.    };  

其中,fd表示监控的文件描述符,ident表示表示监控的事件标识。callback是事件发生时,对应的回调函数。data为传递给回调函数的自定义数据。

mResponses:当前的响应集合。数据结构Response的定义如下:

 

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. struct Response {  
  2.        int events;  
  3.        Request request;  
  4.    };  

mResponseIndex:响应索引号。

mNextMessageUptime:下一个消息处理的时间。

 

接下来,看构造函数声明:

 

    Looper(bool allowNonCallbacks);

参数allowNonCallbacks表示是否允许将文件描述符加入监控对象时,指定回调函数为空。

其实现如下所示:

首先,它创建了一个双向管道,一端读,一端写。并将其设置为非阻塞模式。然后创建epoll实例,将只读端管道文件描述符中入到epoll的监控列表中,这样保护epoll实例中至少包含有一个文件描述符在其事件监控列表中。详细代码如下所示 :

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Looper::Looper(bool allowNonCallbacks) :  
  2.         mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),  
  3.         mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {  
  4.     int wakeFds[2];  
  5.     int result = pipe(wakeFds);  
  6.     LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);  
  7.   
  8.     mWakeReadPipeFd = wakeFds[0];  
  9.     mWakeWritePipeFd = wakeFds[1];  
  10.   
  11.     result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);  
  12.     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",  
  13.             errno);  
  14.   
  15.     result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);  
  16.     LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",  
  17.             errno);  
  18.   
  19.     // Allocate the epoll instance and register the wake pipe.  
  20.     mEpollFd = epoll_create(EPOLL_SIZE_HINT);  
  21.     LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance.  errno=%d", errno);  
  22.   
  23.     struct epoll_event eventItem;  
  24.     memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union  
  25.     eventItem.events = EPOLLIN;  
  26.     eventItem.data.fd = mWakeReadPipeFd;  
  27.     result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);  
  28.     LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",  
  29.             errno);  
  30. }  

再来看与线程相关的几个类的静态函数:

static sp<Looper> prepare(int opts);

将一个Looper实例与调用者所在的线程关联。Opts的值为:

ALOOPER_PREPARE_ALLOW_NON_CALLBACKS或0,它返回该Looper实例。

static void setForThread(const sp<Looper>& looper);

设置looper对象与当前线程关联。如果当前looper对象已经存在,则替换掉。如果looperNULL,则删除当前关联的looper对象。

static sp<Looper> getForThread();

返回当前线程关联的Looper实例。

 

接下来看下两个比较重要的成员函数:

1. int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) 

该函数主要是将fd加入到Looper的事件监控列表中。如果allowNonCallbacksfalse,则必须指定回调函数,且此时ident值为ALOOPER_POLL_CALLBACK(-2),忽略传入的indent的值,而回调函数为空时,传入的ident值不能小于。实际上会通过系统调用epoll_ctl将fd加入到epoll实例的事件监控列表中。同时,也记录下此次的监控信息,封装成一个Request实例,加入到成员变量mRequests当中。如果fd已经存在,则替换掉旧的Request对象。

2. void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler, const Message& message) 

该函数主要作用就是发送一个Message对象,实现就是注册一个MessageEnvelop(消息信封)实例,加入到成员变量mMessageEnvelopes,它是按消息触发的时间排序的。

 

最后,我们来看下它的核心成员函数pollOnce,基本流程图如下所示 :


下面来分析上述过程:

1. Handle response

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. for (;;) {  
  2.         while (mResponseIndex < mResponses.size()) {  
  3.             const Response& response = mResponses.itemAt(mResponseIndex++);  
  4.             int ident = response.request.ident;  
  5.             if (ident >= 0) {  
  6.                 int fd = response.request.fd;  
  7.                 int events = response.events;  
  8.                 void* data = response.request.data;  
  9. #if DEBUG_POLL_AND_WAKE  
  10.                 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "  
  11.                         "fd=%d, events=0x%x, data=%p",  
  12.                         this, ident, fd, events, data);  
  13. #endif  
  14.                 if (outFd != NULL) *outFd = fd;  
  15.                 if (outEvents != NULL) *outEvents = events;  
  16.                 if (outData != NULL) *outData = data;  
  17.                 return ident;  
  18.             }  
  19.         }  

针对回调函数为空的情况,ident值必为一个大于等于0的值(注:有回调函数时,indent的值为-2)。所以上述这段代码只会发生在回调函数为空的情况,此时将返回发生事件的描述符,发生的事件以及返回的数据,供调用者进一步处理。

2. Handle result.

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. for(;;) {  
  2. ...  
  3.        if (result != 0) {  
  4. #if DEBUG_POLL_AND_WAKE  
  5.             ALOGD("%p ~ pollOnce - returning result %d"this, result);  
  6. #endif  
  7.             if (outFd != NULL) *outFd = 0;  
  8.             if (outEvents != NULL) *outEvents = 0;  
  9.             if (outData != NULL) *outData = NULL;  
  10.             return result;  
  11.         }  
  12. ...  
  13. }  

这段代码实际上是根据pollInner的结果进行处理,实际上是针对设置了回调函数的情况,因为设置了回调函数,所以已经对发生的事件做了处理了,所以,不需要将发生事件的相关信息再返回给调用者了。

3. pollInner

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. for(;;) {  
  2. ...  
  3.  result = pollInner(timeoutMillis);  
  4. }  

3.1 Ajust the time out.

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. int Looper::pollInner(int timeoutMillis) {  
  2.     ...  
  3.     // Adjust the timeout based on when the next message is due.  
  4.     if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {  
  5.         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  6.         int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);  
  7.         if (messageTimeoutMillis >= 0  
  8.                 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {  
  9.             timeoutMillis = messageTimeoutMillis;  
  10.         }  
  11.   ...  
  12.   }  
  13.   ...  
  14. }  

为什么要调整超时时间值,原因很简单:因为对于消息来说,可能有多个消息,且每个消息触发的时间点不同,一次事件的触发导致epoll_wait返回并不能处理完所有的消息,所有会多次调用epoll_wait函数,由于超时值是第一次调用时指定的,所以再次调用时,需要重新计算,要去掉已经消耗的时间。代码中now记录当前的时间值,toMillisecondTimeoutDelya(...)计算这本次循环的超时值。上述的判断条件指明了什么情况下需要做些调整:

1. 当前的消息触发时间不早于当前时间。(即消息没有过时)

2. 上轮epoll_wait指定的超时值为-1或一个较大的数值(messageTimeoutMillis)。

3.2 wait for event(epoll wait)

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. ...  
  2.     struct epoll_event eventItems[EPOLL_MAX_EVENTS];  
  3.   int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);  
  4. ...  

主要通过epoll_wait系统调用检测事件的发生。

3.3 handle the event

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. ...  
  2.   for (int i = 0; i < eventCount; i++) {  
  3.         int fd = eventItems[i].data.fd;  
  4.         uint32_t epollEvents = eventItems[i].events;  
  5.         if (fd == mWakeReadPipeFd) {  
  6.             if (epollEvents & EPOLLIN) {  
  7.                 awoken();  
  8.             } else {  
  9.                 ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);  
  10.             }  
  11.         } else {  
  12.             ssize_t requestIndex = mRequests.indexOfKey(fd);  
  13.             if (requestIndex >= 0) {  
  14.                 int events = 0;  
  15.                 if (epollEvents & EPOLLIN) events |= ALOOPER_EVENT_INPUT;  
  16.                 if (epollEvents & EPOLLOUT) events |= ALOOPER_EVENT_OUTPUT;  
  17.                 if (epollEvents & EPOLLERR) events |= ALOOPER_EVENT_ERROR;  
  18.                 if (epollEvents & EPOLLHUP) events |= ALOOPER_EVENT_HANGUP;  
  19.                 pushResponse(events, mRequests.valueAt(requestIndex));  
  20.             } else {  
  21.                 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "  
  22.                         "no longer registered.", epollEvents, fd);  
  23.             }  
  24.         }  
  25.   }  
  26. ...  

对于Looper对象内置的管道,处理EPOLLIN事件,而对于其他监听的文件描述符,则分别记录下EPOLLIN, EPOLLOUT, EPOLLERR, EPOLLHUP并打包成Response对象加入到mResponses中进行处理。

 

3.4 invoke pending message callbacks

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.  // Invoke pending message callbacks.  
  2.     mNextMessageUptime = LLONG_MAX;  
  3.     while (mMessageEnvelopes.size() != 0) {  
  4.         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  5.         const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);  
  6.         if (messageEnvelope.uptime <= now) {  
  7.             // Remove the envelope from the list.  
  8.             // We keep a strong reference to the handler until the call to handleMessage  
  9.             // finishes.  Then we drop it so that the handler can be deleted *before*  
  10.             // we reacquire our lock.  
  11.             { // obtain handler  
  12.                 sp<MessageHandler> handler = messageEnvelope.handler;  
  13.                 Message message = messageEnvelope.message;  
  14.                 mMessageEnvelopes.removeAt(0);  
  15.                 mSendingMessage = true;  
  16.                 mLock.unlock();  
  17.   
  18. #if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS  
  19.                 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",  
  20.                         this, handler.get(), message.what);  
  21. #endif  
  22.                 handler->handleMessage(message);  
  23.             } // release handler  
  24.   
  25.             mLock.lock();  
  26.             mSendingMessage = false;  
  27.             result = ALOOPER_POLL_CALLBACK;  
  28.         } else {  
  29.             // The last message left at the head of the queue determines the next wakeup time.  
  30.             mNextMessageUptime = messageEnvelope.uptime;  
  31.             break;  
  32.         }  
  33.     }  

messageEnvelope.uptime代表该消息被处理的时机,先处理掉已经过时的消息,即messageEnvelope.uptime <= now, 如果还有未过时的消息,则记录下它应该被处理的时间:mNextMessageUptime = messageEnvelope.uptime;也即下次被触发的时间。这个值也作为3.1中调整epoll_wait超时时间的值。

3.5 invoke all response callback

对于回调函数不为空的情形,在事件触发后,就会自动执行调用者提供的回调函数,如下面代码所示:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // Invoke all response callbacks.  
  2.     for (size_t i = 0; i < mResponses.size(); i++) {  
  3.         Response& response = mResponses.editItemAt(i);  
  4.         if (response.request.ident == ALOOPER_POLL_CALLBACK) {  
  5.             int fd = response.request.fd;  
  6.             int events = response.events;  
  7.             void* data = response.request.data;  
  8. #if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS  
  9.             ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",  
  10.                     this, response.request.callback.get(), fd, events, data);  
  11. #endif  
  12.             int callbackResult = response.request.callback->handleEvent(fd, events, data);  
  13.             if (callbackResult == 0) {  
  14.                 removeFd(fd);  
  15.             }  
  16.             // Clear the callback reference in the response structure promptly because we  
  17.             // will not clear the response vector itself until the next poll.  
  18.             response.request.callback.clear();  
  19.             result = ALOOPER_POLL_CALLBACK;  
  20.         }  

三、Looper类应用实例分析

下面来看下Looper类的API的使用。

1. Looper对象初始化

sp<Looper> mLooper = new Looper(true);

...

mLooper.clear();

2. pollOnece函数的使用

 

    StopWatch stopWatch("pollOnce");

    int result = mLooper->pollOnce(1000);

    int32_t elapsedMillis = ns2ms(stopWatch.elapsedTime());

 

返回值为result = ALOOPER_POLL_WAKE

3. 设置CallBack

定义回调函数:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. class CallbackHandler {  
  2. public:  
  3.     void setCallback(const sp<Looper>& looper, int fd, int events) {  
  4.         looper->addFd(fd, 0, events, staticHandler, this);  
  5.     }  
  6.   
  7. protected:  
  8.     virtual ~CallbackHandler() { }  
  9.   
  10.     virtual int handler(int fd, int events) = 0;  
  11.   
  12. private:  
  13.     static int staticHandler(int fd, int events, void* data) {  
  14.         return static_cast<CallbackHandler*>(data)->handler(fd, events);  
  15.     }  
  16. };  
  17.   
  18. class StubCallbackHandler : public CallbackHandler {  
  19. public:  
  20.     int nextResult;  
  21.     int callbackCount;  
  22.   
  23.     int fd;  
  24.     int events;  
  25.   
  26.     StubCallbackHandler(int nextResult) : nextResult(nextResult),  
  27.             callbackCount(0), fd(-1), events(-1) {  
  28.     }  
  29.   
  30. protected:  
  31.     virtual int handler(int fd, int events) {  
  32.         callbackCount += 1;  
  33.         this->fd = fd;  
  34.         this->events = events;  
  35.         return nextResult;  
  36.     }  
  37. };  

使用实例:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Pipe pipe;  
  2.   StubCallbackHandler handler(true);  
  3.   
  4.   pipe.writeSignal();  
  5.   handler.setCallback(mLooper, pipe.receiveFd, ALOOPER_EVENT_INPUT);  
  6.   
  7.   StopWatch stopWatch("pollOnce");  
  8.   int result = mLooper->pollOnce(100);  
  9. int32_t elapsedMillis = ns2ms(stopWatch.elapsedTime());  
  10. .  

result的值为ALOOPER_POLL_CALLBACK。

 

4. Callback为空的情形

若设置Callback为空,此时事件的标识符ident必须是一个大于或等于0的值。如下代码所示:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. const int expectedIdent = 5;  
  2.     void* expectedData = this;  
  3.   
  4.     Pipe pipe;  
  5.   
  6.     pipe.writeSignal();  
  7.     mLooper->addFd(pipe.receiveFd, expectedIdent, ALOOPER_EVENT_INPUT, NULL, expectedData);  
  8.   
  9.     StopWatch stopWatch("pollOnce");  
  10.     int fd;  
  11.     int events;  
  12.     void* data;  
  13.     int result = mLooper->pollOnce(100, &fd, &events, &data);  
  14.     int32_t elapsedMillis = ns2ms(stopWatch.elapsedTime());  

 

此时返回值result等于ident的值。

 

5. 通过Looper发送消息

此种情况下一般不需要调用addFd,通过Looper默认创建的管道来监听事件就行了。它的使用示例如下:

首先要定义一个MessageHandler的派生类,用于处理消息:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. class StubMessageHandler : public MessageHandler {  
  2. public:  
  3.     Vector<Message> messages;  
  4.   
  5.     virtual void handleMessage(const Message& message) {  
  6.         messages.push(message);  
  7.     }  
  8. };  

  接着就可以通过SendMessage相关的函数发送消息到Looper实例上:

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  2.     sp<StubMessageHandler> handler = new StubMessageHandler();  
  3.     mLooper->sendMessageAtTime(now + ms2ns(100), handler, Message(MSG_TEST1));  
  4.   
  5.     StopWatch stopWatch("pollOnce");  
  6.     int result = mLooper->pollOnce(1000);  
  7.     int32_t elapsedMillis = ns2ms(stopWatch.elapsedTime());  
  8.   
  9.     ...  
  10.   
  11.     result = mLooper->pollOnce(1000);  
  12.     elapsedMillis = ns2ms(stopWatch.elapsedTime());  
  13.   
  14.     ...  
  15.     result = mLooper->pollOnce(100);  
  16.     elapsedMillis = ns2ms(stopWatch.elapsedTime());  

第一次

elapsedMillis = 0;

result = ALOOPER_POLL_WAKE

Message size = 0;

第二次

elapsedMillis = 100

result = ALOOPER_POLL_CALLBACK

Message size = 1

第三次

result = ALOOPER_POLL_TIMEOUT

没有消息需要处理。


0 0
原创粉丝点击