(1)使用startService()启动一个service时,Service的生命周期为onCreate->onStartCommand,这时Service正在运行,调用stopService()停止Service,->onDestroy。服务被创建时,调用onCreate方法。服务被启动时,调用onStartCommand。服务被关闭之前调用onDetroy。
注意:理解“服务被启动时,调用onStartCommand ”这句话。startService其实是用于启动Service,只是第一次启动service时,Service还不存在,只能先创建Service(执行onCreate),以后startService启动服务时,都只会执行onStartCommand。
(2)使用bindService是绑定一个Service,生命周期为onCreate->onBind,此时Service会给客户端传回一个IBinder对象,IBinder用于Service和客户端交互。调用unBindService()停止Service,->onUnbind->onDestroy。
注意:在这个过程中不会自动执行onStartCommand,要想使用,可以在onBind中使用startService启动服务,这样就会调用onStartCommand了。
(3)当你定义的Service只能在本应用中使用时,你不应该给service添加intent filter。
“我在一个应用的的Acttivity中通过Intent启动另一个应用中Activity,实际就是跨进程的操作。需要指出的是,如果是在同一个应用中,是不需要Action的,只需要知道被启动Activity的类名就OK,如果被启动的Actiivty在另一个应用中就需要Action了,这点很重要。启动Service或者绑定Service也是这样的。”
Additionally, you can ensure that your service is private to your application only if you include theandroid:exported
attribute and set it to "false"
. This is effective even if your service supplies intent filters.
(4)service是运行在主线程中的,看看下面的描述:
A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.