service是一個提供耗時操作的組件,類似於一個新的線程去處理一些複雜操作,但是執行該操作過程中用戶可以繼續執行其他操作
service不提供直接的和用戶交互的接口,但是用戶應該可以通過activity,notification等組件控制service,同時service也應該把運行狀態反饋給用戶
例如:下載文件,播放音樂等,用戶既要能夠控制該操作,同時又要能夠知道操作的狀態
service聲明
在AndroidManifest.xml 中的 application標籤內聲明service
service可配置屬性爲:
android:name
android:label
android:description
android:icon
android:logo
android:permission
android:process
android:enabled
android:exported
android:stopWithTask
內部子標籤
<intent-filter ></intent-filter>
<meta-data />
service啓動方式
Context.startService()
Context.bindService()
am命令 例如 am startservice -n com.xxx.autoswitcher/com.xxx.autoswitcher.Switcher --es HelloWorld 'start wifi'
PS:對於應用來說 service有2中類型,一種是自己的service(LocalService) 另一種是別人的service(RemoteService)
LocalService 應用可以直接引用對應的類和函數 參考 com.example.android.apis.app.LocalService.java
Remoteervice 應用不能直接引用對應的類和函數,所以需要AIDL 參考 com.example.android.apis.app.RemoteService.java
com.example.android.apis.app.IRemoteService.aidl
============================ 當寫一個**.aidl之後,會在gen下面生成對應的java文件,這個文件需要分析
service的聲明週期可以參考官方圖示
2、service_binding_tree
今天在練習bindService時遇到問題
1、onServiceConnected 中的log沒有打印出來
原來 service中 onBind函數默認返回的是null 也就是沒有IBinder 所以沒有connection中的log
2、java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.kybsy.servicedetails.MyService$LocalBinder
就是在connected 中 mMyService = ((MyService.LocalBinder)service).getService();
原來是service配置了android:process=":remote" 導致無法轉換 估計需要 IPC纔可以