要实现的功能:在android Framework层被裁剪掉的情况下,实现监听长按的物理power按键,实现长按3秒后关机功能;

思路:使用event epoll,非阻塞式IO操作,同时避免无差别轮询,做到避免忙轮和无差别轮询提高效率;

要用到的epoll函数:

epoll_create(EPOLL_SIZE_HINT);epoll_wait(mEpollFd,mPendingEventItems,8,-1);epoll_ctl(mEpollFd,EPOLL_CTL_ADD,fd,&eventItem)epoll_ctl(mEpollFd,EPOLL_CTL_DEL,fd,&eventItem);


下面是实现的过程:

intmain(intargc,char*argv[]){ALOGI("robottestrobotpower");structitimervalold_value;inttap_power_time=0;inttap_power_type=0;inttap_power_code=0;inttap_power_value=0;structitimervaltick;intmEpollFd;constintEPOLL_SIZE_HINT=8;constchar*DEV_INPUT="/dev/input/event1";structepoll_eventmPendingEventItems[8];unsignedcharbuf[1024]={0};structinotify_event*event=NULL;structRawEvent*readBuffer=(structRawEvent*)malloc(sizeof(structRawEvent));mEpollFd=epoll_create(EPOLL_SIZE_HINT);intfd=open(DEV_INPUT,O_RDWR|O_CLOEXEC);/**structepoll_event{*uint32_tevents;//epollevents(bitmask)*epoll_data_tdata;//Userdata*};*/structepoll_eventeventItem;memset(&eventItem,0,sizeof(eventItem));/***EPOLLIN:hasdatatoread*EPOLLOUT:hasdatatowrite*/eventItem.events=EPOLLIN;/***EPOLL_CTL_ADD:addfdtowatchinglist*EPOLL_CTL_DEL:removefdfromwatchinglist*/if(epoll_ctl(mEpollFd,EPOLL_CTL_ADD,fd,&eventItem)==-1){exit(0);}for(;;){/***parameter-1:waituntileventoccur;*0:returnimmediatelywhendealwithanon-blockevent*/epoll_wait(mEpollFd,mPendingEventItems,8,-1);int32_treadSize=read(fd,readBuffer,sizeof(structinput_event));structinput_event*event=(structinput_event*)readBuffer;tap_power_time=(int)event->time.tv_sec;tap_power_type=event->type;tap_power_code=event->code;tap_power_value=event->value;if(is_power_down_key(tap_power_type,tap_power_code,tap_power_value)){ALOGI("robotpowerdownkey");signal(SIGALRM,handle_exit);memset(&tick,0,sizeof(tick));tick.it_value.tv_sec=3;tick.it_value.tv_usec=0;setitimer(ITIMER_REAL,&tick,NULL);}elseif(is_power_up_key(tap_power_type,tap_power_code,tap_power_value)){tick.it_value.tv_sec=0;tick.it_value.tv_usec=0;setitimer(ITIMER_REAL,&tick,NULL);}}epoll_ctl(mEpollFd,EPOLL_CTL_DEL,fd,&eventItem);return0;}

structRawEvent{int32_twhen;int32_tdeviceId;int32_ttype;int32_tcode;int32_tvalue;};voidhandle_exit(intsig){ALOGI("robot3secondtimeout,nowshutdown!");system("reboot-p");}intis_power_down_key(inttype,intcode,intvalue){intis_down=0;is_down=(type==1)&&(code==116)&&(value==1);returnis_down;}intis_power_up_key(inttype,intcode,intvalue){intis_up=0;is_up=(type==1)&&(code==116)&&(value==0);returnis_up;}