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. History(历史)命令用法 15 例

    如果你经常使用 Linux 命令行,那么使用 history(历史)命令可以有效地提升你的效率.本文将通过实例的方式向你介绍 history 命令的 15 个用法. 使用 HISTTIMEFORMAT ...

  2. 九度OJ1004 Median

    题目描写叙述: Given an increasing sequence S of N integers, the median is the number at the middle positio ...

  3. leetCode 67.Add Binary (二进制加法) 解题思路和方法

    Given two binary strings, return their sum (also a binary string). For example, a = "11" b ...

  4. 深入浅出Redis(二)高级特性:事务

    第一篇中介绍了Redis是一个强大的键-值仓储,支持五种灵活的数据结构.其实,Redis还支持其他的一些高级特性:事务.公布与订阅.管道.脚本等,本篇我们来看一下事务. 前一篇中我们提到,在Redis ...

  5. 关于对FLASH开发,starling、starling feathers、starling MVC框架的理解

    说在前头:楼主之前没有不论什么flash开发经验,仅仅是从一次尝试中总结自己的理解和经验而已.假设有写的不正确的地方,欢迎大家指正. 前一段时间尝试想用flash(as3)又一次制作一下之前做的一个游 ...

  6. Codeforces Round #316 (Div. 2) C. Replacement

    题意:给定一个字符串,里面有各种小写字母和' . ' ,无论是什么字母,都是一样的,假设遇到' . . ' ,就要合并成一个' .',有m个询问,每次都在字符串某个位置上将原来的字符改成题目给的字符, ...

  7. android ImageUtils 图片处理工具类

    /** * 加入文字到图片.相似水印文字. * @param gContext * @param gResId * @param gText * @return */ public static Bi ...

  8. 变量的命名和if语句

    1. 计算机是什么 基本组成: cpu: 主频, 核数(16) 内存:大小(8G, 16G, 32G) 型号: DDR3, DDR4, DDR5,  主频(海盗船,玩家国度) 显卡: 显存.型号(N- ...

  9. 将前端js异步调用的多个服务合并为一个前端服务

    将前端js异步调用的多个服务合并为一个前端服务 1. 减少前端js异步请求的次数改善浏览体验 2. 方便地针对单个接口做异常降级处理

  10. mysql 时间间隔计算

    业务需求说明 早8:30点执行该sql,写入定时脚本 [在稳定前,需要手动复检] INSERT INTO test_error ( url, no_open_times, no_ad_times, o ...