您的位置:首页 > 移动开发 > Android开发

Android管理服务(Service)的生命周期(lifecycle)

2016-09-25 13:14 615 查看
服务(Service)的生命周期要比Activity简单的多。尽管如此,由于服务会在用户不知情的情况下运行在后台,你也要严密监视你的服务是如何创建和销毁的。

服务的生命周期(从创建到销毁)有两条路径:

被启动的服务(started service)

当服务被一个组件通过startService()函数启动后,这个服务就会独立的运行,必须被自己用stopSelf()函数或者其他组件用stopService()函数来停止。一旦服务被停止,系统就会销毁它。

绑定的服务(bound service)

当一个服务被另一个组件通过bindService()函数创建后,客户就会通过IBinder接口和服务进行交互。客户可以通过unbindService()函数关闭连接(解除绑定 )。多个客户可以绑定到同一个服务,当所有客户都关闭和服务连接(解除绑定 )后,系统会销毁服务(服务没有必要自己停止自己)。

这两条路径并不是完全分离的。这是因为你可以绑定一个被启动的服务(started service)。例如,一个音乐播放服务可能被startService()函数启动来播放一首歌曲。过了一会儿,可能用户想要在播放器做一些操作或者获取关于当前歌曲的信息,一个activity就会通过bindService()函数绑定到该服务。这种情况下,调用stopService() 或 stopSelf() 不会真的停止服务,知道所有绑定的客户都解除绑定(关闭连接)。

实现生命周期器回调函数

如同activity,服务(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 void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}


注意:与activity不同的是,服务的生命周期函数不需要你调用父类相应的函数。



注:左边的图是被
d1bc
启动的服务(started service)的生命周期,右边的图是被绑定的服务(bound service)的生命周期。

通过实现这些方法,你可以监视两个嵌套的生命周期循环:

整个生命时间,服务从onCreate()函数被调用一直到onDestroy()函数返回。就像activity一样,服务在onCreate()函数中做初始化操作,在onDestroy()函数中释放剩余的资源。例如,一个音乐播放服务在onCreate()函数中创建一个线程用于音乐播放,然后在onDestroy()函数中停止该线程。

onCreate()和onDestroy()函数会被所有的服务所调用,无论他是被startService()函数创建的还是被bindService()函数创建的。

活跃的生命时间,开始于onStartCommand()或onBind()函数被调用。每个函数都会分别被传入intent。

如果是被启动的服务,他的活跃生命时间会和整个生命时间一同结束(在onStartCommand()函数返回后,服务依然是活跃状态)。如果是被绑定的服务,活跃生命时间会在onUnbind()函数返回后结束。

注意:尽管一个启动的服务会被stopSelf()函数或stopService()函数所停止,但是没有响应的回调函数(不存在onStop()回调函数)。所以,当服务被停止销毁的过程中,只有onDestroy()一个回调函数会响应。

这个图画的是服务典型的回调方法。尽管我们把被启动的服务和被绑定的服务分开画,但是我们一定要注意,不管服务是如何被创建的,它都允许客户绑定它。所以一个通过onStartCommand()方法启动的服务(started service)依然会收到onBind()调用(当客户调用了bindService())。

参考:http://developer.android.com/guide/components/services.html#Lifecycle

转载自:http://blog.csdn.net/oracleot/article/details/18818575
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐