關鍵詞:四大組件 / Activity / Service / BroadcastReceiver / ContentPRovider
本次筆記主要梳理了四大組件的進一步認識,為今后更進一步了解四大組件的工作原理做個準備,溫故知新、查漏補缺。
Android 四大組件中除了 BroadcastReceiver 以外,其它三種組件都必須只在 AndroidManifest 中注冊,而 BroadcastReceiver 既可以在 Manifest 中注冊也可以通過代碼來注冊。Activity、Service、BroadcastReceiver 需要借助 Intent 來調用,而 ContentProvider 無需借助 Intent。
強調一下 Service 的兩種狀態: 啟動狀態 —— 主要用于執行后臺計算; 綁定狀態 —— 主要用于其它組件和 Service 的交互; 這兩種狀態是可以共存的,既可以處于啟動狀態也可以同時處于綁定狀態。
Intent intentService = new Intent(this, MyService.class);startService(intentService);Intent intentService = new Intent(this, MyService.class);bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);來了解一下 Google 官方的說明:
對于 startService: Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single Operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself. 用 startService 啟動,這個 Service 不會跟隨者啟動它的 component 消減,而且原則上不能與 UI 互動;
對于 bindService: A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (ipC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed. 用 bindService 的情況下,此 service 可以跟 component 進行溝通,甚至可以做到 IPC
小結: bindService 和 startService 最主要的差別在于其本身的 LifeCycle 以及 bindService 可以用來做 IPC(可以讓你的 service 和 UI 溝通)
當通過 send 方法來發送廣播的時候,AMS 會查找出匹配的廣播接收者并將廣播發送給它們處理。 廣播發送的幾種類型有:普通廣播、有序廣播和粘貼廣播;它們的發送/接收過程是類似的;
當 ContentProvider 所在的進程啟動的時候,ContentProvider 的 onCreate 要先于 Application 的 onCreate 而執行,這在四大組件中是一個很少有的現象;
End.
Note by HF. Learn from 《Android 開發藝術探索》
新聞熱點
疑難解答