Android 四大組件
- 四大組件的分類
注冊(cè)方式上
Activity Service ContentProvider 必須在AndroidManifest中注冊(cè),BroadcastReceiver可以在清單文件注冊(cè)蝶念,也可以在代碼中注冊(cè)
調(diào)用方式上
Activity Service BroadcastReceiver必須借助Intent啟動(dòng)憎茂,ContentProvider不需要
Service
- Service有兩種狀態(tài) 啟動(dòng)狀態(tài)和綁定狀態(tài)
- Service啟動(dòng)方式有顯示啟動(dòng)和隱式啟動(dòng)
同一個(gè)包中阅畴,顯示啟動(dòng)和隱式啟動(dòng)都可以用嫉拐,不同包只能用隱式啟動(dòng)
隱士啟動(dòng)通過設(shè)置Action的方式啟動(dòng)
***** 需要注意的是在5.0上采用隱式啟動(dòng)時(shí)梦湘,會(huì)出現(xiàn)java.lang.IllegalArgumentException: Service Intent must be explicit異常沃暗。也就是說Service的Intent必須明確月洛。
解決方法就是給Intent設(shè)置一下具體的包名,指明具體是哪個(gè)包啟動(dòng)的Service孽锥。
intent.setPackage("com.android.vending")
或者通過給Intent設(shè)置ComponentName的方式啟動(dòng)
或者通過隱式Intent反查找Component轉(zhuǎn)化成顯示Intent啟動(dòng)嚼黔。
- Service 本身運(yùn)行與主線程中
- ContentProvider 中的query,insert,delete,update運(yùn)行與binder線程池中
- ContentProvider不需要手動(dòng)停止
-
Instrumentation 主要功能完成Application,Activity實(shí)例的創(chuàng)建惜辑,生命周期調(diào)用的具體實(shí)現(xiàn)唬涧。
-
Activity的啟動(dòng)流程
一張簡(jiǎn)單泳道圖 從startActivity()開始
- Activity 的Context mBase (getBaseContext)賦值是在attach中的attachBaseContext方法中,創(chuàng)建是在ActivityThread中的performLaunchActivity中創(chuàng)建的Context盛撑,傳遞給Activity.
Context appContext = createBaseContextForActivity(r, activity);
-
Activity App的Context創(chuàng)建實(shí)現(xiàn)都是在ContextImpl中實(shí)現(xiàn)
- BroadCastReceiver不能bindService,會(huì)報(bào)錯(cuò)碎节,具體看ContextImpl
- onStartCommand方法返回值意義:
- START_STICKY
服務(wù)被異常殺死后,會(huì)被重新調(diào)起抵卫,但傳入onStartCommand的Intent為null狮荔,適用于不執(zhí)行命令的媒體播放器,無限期運(yùn)行等待著工作的到來
- START_NOT_STICKY
服務(wù)被殺死后就退出了啟動(dòng)狀態(tài)介粘,除非重新調(diào)用startService啟動(dòng)服務(wù)殖氏,不然服務(wù)不會(huì)運(yùn)行。
- START_REDELIVER_INTENT
服務(wù)被異常Kill后姻采,系統(tǒng)會(huì)重啟服務(wù)雅采,并且保留kill之前的Intent,并且在該服務(wù)調(diào)用stopSelf之前,一直保留Intent,適用于應(yīng)該立即恢復(fù)正在執(zhí)行的工作的服務(wù)婚瓜,如文件下載
- START_STICKY_COMPATIBILITY
START_STICKY的兼容版本宝鼓,但不保證服務(wù)被終止后一定能重啟。
- BroadcastReceiver 需要在合適的時(shí)機(jī)unRegiestReceiver()
- 靜態(tài)廣播在應(yīng)用安裝時(shí)由系統(tǒng)完成注冊(cè)闰渔,具體來說是由PMS(PackageManagerService)完成具體注冊(cè)任務(wù)
除了廣播外席函,其他三大組件也是由PMS在安裝時(shí)完成注冊(cè)
- onReceive()方法運(yùn)行在主線程中
- Android 本地廣播LocalBroadcastManager
只在app內(nèi)傳播的廣播,為單例模式冈涧。
- ActivityThread 創(chuàng)建Application對(duì)象并加載ContentProvider
ActivityThread會(huì)先加載ContentProvider,然后執(zhí)行Application的onCreate()
ActivityThread.handleBindApplication->LoadApk.makeApplication()->ActivityThread.installContentProviders()->mInstrumentation.callApplicationOnCreate->Applicaiton.onCreate()
- ContentProvider提供insert,delete,update,query
- ContentProvider默認(rèn)在程序中都是單例的茂附,如果指定android:multiProcess為true,則為多例督弓,每個(gè)進(jìn)程中都會(huì)有一個(gè)ContentProvider實(shí)例
- Context.getContentResolver 返回ApplicationContentResolver
- ApplicationContentResolver是ContentResolver的實(shí)現(xiàn)類营曼,完成與AMS間的bind通信