Android管理服务(Service)的生命周期(lifecycle)
- 被启动的服务(started service)
- 绑定的服务(bound service)
public class ExampleService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
@Override
public voidonCreate
() {
// The service is being created
}
@Override
public intonStartCommand
(Intent intent, int flags, int startId) {
// The service is starting, due to a call tostartService()
return mStartMode;
}
@Override
public IBinderonBind
(Intent intent) {
// A client is binding to the service withbindService()
return mBinder;
}
@Override
public booleanonUnbind
(Intent intent) {
// All clients have unbound withunbindService()
return mAllowRebind;
}
@Override
public voidonRebind
(Intent intent) {
// A client is binding to the service withbindService()
,
// after onUnbind() has already been called
}
@Override
public voidonDestroy
() {
// The service is no longer used and is being destroyed
}
}
- 整个生命时间,服务从onCreate()函数被调用一直到onDestroy()函数返回。就像activity一样,服务在onCreate()函数中做初始化操作,在onDestroy()函数中释放剩余的资源。例如,一个音乐播放服务在onCreate()函数中创建一个线程用于音乐播放,然后在onDestroy()函数中停止该线程。
- 活跃的生命时间,开始于onStartCommand()或onBind()函数被调用。每个函数都会分别被传入intent。
如果是被启动的服务,他的活跃生命时间会和整个生命时间一同结束(在onStartCommand()函数返回后,服务依然是活跃状态)。如果是被绑定的服务,活跃生命时间会在onUnbind()函数返回后结束。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。