資源描述:
《android深入四大組件(四)廣播的注冊(cè)、發(fā)送和接收過程》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、Android深入四大組件(四)廣播的注冊(cè)、發(fā)送和接收過程1.廣播的注冊(cè)過程BroadcastReceiver的注冊(cè)分為兩種,分別是靜態(tài)注冊(cè)和動(dòng)態(tài)注冊(cè),靜態(tài)注冊(cè)在應(yīng)用安裝時(shí)由PackageManagerService來完成注冊(cè)過程,關(guān)于這一過程,我會(huì)在后續(xù)的介紹PackageManagerService文章中詳細(xì)介紹。這里只介紹BroadcastReceiver的動(dòng)態(tài)注冊(cè)。要想動(dòng)態(tài)注冊(cè)BroadcastReceiver,需要調(diào)用registerReceiver方法,它的實(shí)現(xiàn)在ContextWrapper中,代碼如下所示。frameworks/base/core/J
2、ava/android/content/ContextWrapper.javaOverridepublicIntentregisterReceiver(BroadcastReceiverreceiver,IntentFilterfilter){returnmBase.registerReceiver(receiver,filter);}ContextImpl的registerReceiver方法有很多重載的方法最終會(huì)調(diào)用registerReceiverInternal方法:frameworks/base/core/java/android/app/ContextI
3、mpl.javaprivateIntentregisterReceiverInternal(BroadcastReceiverreceiver,intuserId,IntentFilterfilter,StringbroadcastPermission,Handlerscheduler,Contextcontext){IIntentReceiverrd=null;if(receiver!=null){if(mPackageInfo!=null&&context!=null){//1if(scheduler==null){scheduler=mMainThread.
4、getHandler();}rd=mPackageInfo.getReceiverDispatcher(receiver,context,scheduler,mMainThread.getInstrumentation(),true);//2}else{if(scheduler==null){scheduler=mMainThread.getHandler();}rd=newLoadedApk.ReceiverDispatcher(receiver,context,scheduler,null,true).getIIntentReceiver();//3}}try
5、{finalIntentintent=ActivityManagerNative.getDefault().registerReceiver(mMainThread.getApplicationThread(),mBasePackageName,rd,filter,broadcastPermission,userId);//4if(intent!=null){intent.setExtrasClassLoader(getClassLoader());intent.prepareToEnterProcess();}returnintent;}catch(Remote
6、Exceptione){throwe.rethrowFromSystemServer();}在注釋1處判斷如果LoadedApk類型的mPackageInfo不等于null并且context不等null就調(diào)用注釋2處的代碼通過mPackageInfo的getReceiverDispatcher方法獲取rd對(duì)象,否則就調(diào)用注釋3處的代碼來創(chuàng)建rd對(duì)象。注釋2和3的代碼的目的都是要獲取IIntentReceiver類型的rd對(duì)象,IIntentReceiver是一個(gè)Binder接口,用于進(jìn)行跨進(jìn)程的通信,它的具體實(shí)現(xiàn)在LoadedApk.ReceiverDispatc
7、her.InnerReceiver,如下所示。frameworks/base/core/java/android/app/LoadedApk.javastaticfinalclassReceiverDispatcher{finalstaticclassInnerReceiverextendsIIntentReceiver.Stub{finalWeakReferencemDispatcher;finalLoadedApk.ReceiverDispatchermStrongRef;InnerReceiver(
8、Loade