c++实现android系统的handler

1、android的hander的确非常好用。

2、我们能不能用c++也实现一个类似功能hander这样的想法马上就被付诸实践。

3、首先介绍一个android hander的用法。

    照搬别人的吧,毕竟很多这样的文章了。https://www.cnblogs.com/wlming/p/5553207.html

4、这里hander旨在解决消息的异步发送,同样拥有delay发送消息机制。

相应的应用场景:应用触发显示,交互控制命令等。

5、这个是本文章的大致结构。


6、测试代码使用方法如下:

 
 

#include "WKMessageQueue.h"

#include "WKMessage.h"

 #include "WKLooper.h"
 #include "WKHandler.h"
  
 #include <unistd.h>
  
 #include <utils.h>
  
 #define MODULE_NAME "WKMESAAGE_TEST"
  
 using namespace android;
  
 int main(void)
 {
 int cnt = 0;
  
 WKHandler *handler = new WKHandler();
 WKLooper *looper = new WKLooper();
 handler->setLooper(looper);
 looper->loop();
  
 while(1)
 {
 WKMessage *msg = WKMessage::obain(cnt++, handler);
 handler->sendMessage(msg);
 if(cnt >10)
 break;
 usleep(1000000);
 }
  
 //休眠等待处理完
 sleep(10);
 LOGD("now,sPoolSize:%d,sPool is %s.",WKMessage::sPoolSize,WKMessage::sPool==NULL?"null":"not null");
 }

7、运行效果如下所示:


7、代码下载地址:

    https://github.com/huanhuankangwang/UDI/tree/master/hanlder


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,Android中的Handler机制有一定的不同,因为C++并不支持Java中的线程和Looper机制。不过我们可以使用一些第三方库来实现类似的功能,比如libevent和libuv。以下是使用libevent实现Android中AHandler与子线程关联的示例代码: ```c++ #include <event2/event.h> #include <event2/thread.h> class MyHandler : public AHandler { public: MyHandler(struct event_base* base) : base_(base) {} virtual void handleMessage(const AMessage& msg) { // 处理消息 } void postMessage(const AMessage& msg) { // 将消息发送到子线程 event_base_once(base_, -1, EV_TIMEOUT, [](evutil_socket_t fd, short what, void* args) { MyHandler* handler = static_cast<MyHandler*>(args); handler->handleMessage(msg); }, this, nullptr); } private: struct event_base* base_; }; void* thread_func(void* arg) { event_base* base = event_base_new(); MyHandler* handler = new MyHandler(base); ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); ALooper_addFd(looper, event_base_get_fd(base), 0, ALOOPER_EVENT_INPUT, nullptr, handler); event_base_dispatch(base); return nullptr; } int main(int argc, char** argv) { evthread_use_pthreads(); pthread_t thread; pthread_create(&thread, nullptr, thread_func, nullptr); MyHandler* handler = new MyHandler(nullptr); // 将消息发送到子线程 handler->postMessage(msg); pthread_join(thread, nullptr); return 0; } ``` 在这个示例代码中,我们首先使用event_base创建了一个子线程的事件循环,然后在MyHandler中通过event_base_once将消息发送到子线程。在主线程中,我们创建了一个MyHandler用于接收子线程返回的消息,并将其与主线程的ALooper关联。这样,当我们发送消息时,MyHandler就会在子线程中接收到并处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值