Managing the Lifecycle of a Service

  The lifecycle of a service is much simpler than that of an activity. However, it's even more important that you pay close attention to how your service is created and destroyed, because a service can run in the background without the user being aware.

  The service lifecycle—from when it's created to when it's destroyed—can follow two different paths:

  • A started service

    The service is created when another component calls startService(). The service then runs indefinitely and must stop itself by calling stopSelf(). Another component can also stop the service by calling stopService(). When the service is stopped, the system destroys it..

  • A bound service

    The service is created when another component (a client) calls bindService(). The client then communicates with the service through an IBinder interface. The client can close the connection by calling unbindService(). Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. (The service does not need to stop itself.)

  These two paths are not entirely separate. That is, you can bind to a service that was already started with startService(). For example, a background music service could be started by calling startService() with an Intent that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService(). In cases like this, stopService() or stopSelf() does not actually stop the service until all clients unbind.

 started和bound类的service 生命周期函数不是完全独立的,started的service也可以被绑定,这时要先解绑才能停止。

Implementing the lifecycle callbacks 如何实现service生命周期函数

  Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service demonstrates each of the lifecycle methods:

 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
}
}

  Note: Unlike the activity lifecycle callback methods, you are not required to call the superclass implementation of these callback methods.

 service的生命周期函数,不是必需调用父类的,如super.xxx。

      

  Figure 2. The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService().

  By implementing these methods, you can monitor two nested loops of the service's lifecycle:

  • The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns. Like an activity, a service does its initial setup in onCreate() and releases all remaining resources in onDestroy(). For example, a music playback service could create the thread where the music will be played in onCreate(), then stop the thread in onDestroy().

    The onCreate() and onDestroy() methods are called for all services, whether they're created by startService() or bindService().

  • The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each method is handed the Intent that was passed to either startService() or bindService(), respectively.

    If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after onStartCommand() returns). If the service is bound, the active lifetime ends when onUnbind() returns.

    -started的service一直存活,直到系统清理内存时,才有可能杀死它。
    -bound的service活到onUnbind()函数返回。

  Note: Although a started service is stopped by a call to either stopSelf() or stopService(), there is not a respective callback for the service (there's no onStop() callback). So, unless the service is bound to a client, the system destroys it when the service is stopped—onDestroy() is the only callback received.

  Figure 2 illustrates the typical callback methods for a service. Although the figure separates services that are created by startService() from those created by bindService(), keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it. So, a service that was initially started with onStartCommand() (by a client calling startService()) can still receive a call to onBind() (when a client calls bindService()).

  For more information about creating a service that provides binding, see the Bound Services document, which includes more information about the onRebind() callback method in the section about Managing the Lifecycle of a Bound Service.

Service官方教程(4)两种Service的生命周期函数的更多相关文章

  1. Service的两种用法及其生命周期

    先来一点基础知识: Service 是android的四大组件之一,与Activity同属于一个级别,它是运行在后台进行服务的组件(例如在后台播放的音乐,播放音乐的同时并不影响其他操作).Servic ...

  2. 两种Service如何一起使用

    1.先是调用startservice来开启服务,并在且在后台一起运行. 2.在调用bindservice,获取中间对象. 3.unbindservice解绑服务. 4.最后在调用stopservice ...

  3. service的生命周期以及两种service的差异

    可以看到,两种service的生命周期都相对简单,有一点不同的是,Intentservice每次调用的时候都执行onstartcommand,而boundservice一旦启动了之后,就不会每次执行o ...

  4. Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。

    1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...

  5. org.springframework.stereotype.Service和com.alibaba.dubbo.config.annotation.Service两种service的区别

    这两个Service,都可以在service类头上使用@Service的注解,于是我就写错了,查了半天才发现.他们的区别大概是这个样子的: org.springframework.stereotype ...

  6. 关于android中两种service的编写简单总结

    1.startservice (两种方法,继承service类或者继承intentservice 类) 继承service类,在onstartcommend重载方法中实现业务逻辑的处理,如果耗时过长最 ...

  7. Service官方教程(2)*IntentService与Service示例、onStartCommand()3个返回值的含义。

    1.Creating a Started Service A started service is one that another component starts by calling start ...

  8. Service官方教程(1)Started与Bound的区别、要实现的函数、声明service

    Services 简介和分类 A Service is an application component that can perform long-running operations in the ...

  9. Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信

    Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...

随机推荐

  1. StringUtil内部方法差异

    StringUtil 的 isBlank.isEmply.isNotEmpty.isNotBlank 区别   String.trim()方法: trim()是去掉首尾空格   append(Stri ...

  2. 怎样使用SSH连接OpenStack上的云主机

    转载请注明出处.否则将追究法律责任http://blog.csdn.net/xingjiarong/article/details/47021815 在上一篇博客中我介绍了怎样在OpenStack中创 ...

  3. js 终止执行的实现方法

    终止JS运行有如下几种可能: 1.终止函数的运行的方式有两种 (1)在函数中使用return,则当遇到return时,函数终止执行,控制权继续向下运行 (2)在函数中使用try-catch异常处理,需 ...

  4. 用户代码未处理 UpdateException

    无法更新 EntitySet"Project_project",由于它有一个 DefiningQuery.而 <ModificationFunctionMapping> ...

  5. 【转载】TCP和TCP/IP的区别

    TCP/IP协议(Transmission Control Protocol/Internet Protocol)叫做传输控制/网际协议, 又叫网络通讯协议,这个协议是Internet国际互联网络的基 ...

  6. 项目实战之玩转div+css制作自己定义形状

    项目需求 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/diss ...

  7. 【HRS项目】Axure兴许问题解决---与SVN结合

    上一篇博客介绍了Axure的团队开发用法,http://blog.csdn.net/u013036274/article/details/50999139,可是再用的时候发现会出现这种问题,例如以下图 ...

  8. Sublime Text 3.3143最新注册码

    Sublime Text3之前用的是老版本,昨天手贱点了更新,就要重新激活,网上找了好多都是之前版本的,以下给干货 —– BEGIN LICENSE —– TwitterInc User Licens ...

  9. 必备java参考资源列表

    现在开始正式介绍这些参考资源. Web 站点和开发人员 Web 门户 网络无疑改变了共享资源和出版的本质(对我也是一样:您正在网络上阅读这篇文章),因此,从每位 Java 开发人员都应该关注的关键 W ...

  10. Delphi汉字简繁体转换代码(分为D7和D2010版本)

    //delphi 7 Delphi汉字简繁体转换代码unit ChineseCharactersConvert; interface uses   Classes, Windows; type   T ...