Service启动&&绑定服务与某个Activity&&service的生命周期
1、一个service在一个操作系统中最多只有一个实例。
2、不需要界面。
3、使用Service:
- service类onStartCommand函数(Called by the system every time a client explicitly starts the service by calling(
android.content.Context.startService). - servece类
public IBinder onBind(Intent intent) {
return new Binder();
} - startService(new Intent(MainActivity.this,MyService.class))与stopService(new Intent(MainActivity.this,MyService.class))
-
<service
android:name=".MyService"
android:enabled = "true"
android:exported = "true">
</service>
4、绑定服务与某个Activity:
- Activity需要implements ServiceConnection。并重写两个函数onServiceConnected和onServiceDisconnected。
- bindService(new Intent(MainActivity.this,MyService.class), this,Context.BIND_AUTO_CREATE);
- unbindService(this);
5、service的生命周期:
-
使用context.startService() 启动Service
其生命周期为context.startService() ->onCreate()- >onStart()->Service running-->(如果调用context.stopService() )->onDestroy() ->Service shut down
如果Service还没有运行,则android先调用onCreate()然后调用onStart();
如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。
调用stopService的时候直接onDestroy,
如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。
该Service的调用者再启动起来后可以通过stopService关闭Service。
所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy
对于bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service running-->onUnbind() -> onDestroy() ->Service stop
onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。
这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,
Srevice就会调用onUnbind->onDestroy相应退出。
所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。
一但销毁activity它就结束,如果按home把它放到后台,那他就不退出。 ![]()
- 在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),
其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。


浙公网安备 33010602011771号