可以参考 apidemo 和 google官方文档 --- 2个代码是不一样的可以借鉴
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的声明周期可以参考官方图示
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才可以