欢迎来到天天文库
浏览记录
ID:12977761
大小:106.50 KB
页数:7页
时间:2018-07-20
《如何编写android service》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Android的核心框架技術之1:如何撰寫第一個核心服務 如何撰寫自己的第一個核心服務呢? by高煥堂**高煥堂的最新課程消息** 1.要點:l 核心服務通常在獨立的進程(Process)裡執行。l 必須提供IBinder介面,讓應用程式可以進行跨進程的綁定(Binding)和呼叫。l 因為共用,所以必須確保多線裎安全(Thread-safe)。l 以C++類別定義,誕生其物件,透過SM之協助,將該物件參考值傳給IServiceManager
2、::addService()函數,就加入到BinderDriver裡了。l 應用程式可透過SM之協助而遠距綁定該核心服務,此時SM會回傳IBinder介面給應用程式。l 應用程式可透過IBinder::transact()函數來與核心服務互傳資料。 2. 入門級範例:將AddService核心服務加入BinderDriver此範例功能為簡單的整數加法(Add)運算,此核心服務命名為AddService。Step-1:以C++撰寫AddService類別,其完整程式碼為: /*---AddServ
3、ice.h定義檔 ---*///AddService.h#ifndefANDROID_GUILH_ADD_SERVICE_H#defineANDROID_GUILH_ADD_SERVICE_H#include#include#include#include namespaceandroid{classAddService:publicBBinder{ mutable Mutex mLock
4、; int32_t mNextConnId; public: static intinstantiate();AddService(); virtual~AddService(); virtualstatus_tonTransact( uint32_t,constParcel&,Parcel*,uint32_t);}};//namespace#endif /*---AddService.cpp實作檔 ---*///AddService.cpp#inc
5、lude"AddService.h"#include#include namespaceandroid{staticstructsigactionoldact;staticpthread_key_tsigbuskey; intAddService::instantiate(){ LOGE("AddServiceinstantiate"); intr=defaultServiceManager()->a
6、ddService( String16("guilh.add"),newAddService()); LOGE("AddServicer=%d",r);returnr;} AddService::AddService() { LOGV("AddServicecreated"); mNextConnId=1; pthread_key_create(&sigbuskey,NULL); } AddService::~AddService()
7、 { pthread_key_delete(sigbuskey); LOGV("AddServicedestroyed"); } status_tAddService::onTransact( uint32_tcode,constParcel&data,Parcel*reply,uint32_tflags){ switch(code){ case0:{ pid_tpid=data.readInt32(); intnu
8、m=data.readInt32(); num= num+1000; reply->writeInt32(num); returnNO
此文档下载收益归作者所有