必须谨记的几点:

1. service的所有onXXXX( )都是运行在main thread,包括onStartCommand()。Because all service's onXXXX() functions are called via handleMessage() of handler which is created with the main thread's loop.

client的onServiceConnected()和onServiceDisonnected()也都是运行在main thread,because they are also called via handler which is created with the main thread's loop,

2. All IPC are executed via binder and executed in the binder thread. Android app framework will create binder thread during startup which is created using native code(such thread may be spawned if necessary,系统会维护一个binder thread的线程池,以保证所有的IPC都可以被handle).

3. onStartCommand()不需要考虑线程安全,因为onStartCommand() is executed in the main thread in turn。But if we use bound service, 需要考虑线程安全,因为all IPC are executed in the binder thread(binder thread maybe multiple).

4. ADIL是同步调用,而service的所有其它接口(bind, unbind, startService, stopService)都是异步接口,立即返回。

service有两种启动方式:Started和Bound。

Started方式:使用startService()启动。一旦启动,service will run indefinitely,unless stopSelf() or stopService() is called。

优点:使用简单,client端只需要简单的调用startService(),service端只需要在onStartCommand()进行处理。

缺点:

1. 必须调用stopSelf() or stopService()关闭service;

2. client端无法获取返回值(虽然可以通过向service传递PendingIntent for Broadcast实现);

3. 单向调用,只能由client端向service端发送intent。

Bound方式:使用bindService()启动。一旦启动,service will run indefinitely。 Multiple components can bind to the same service, but only when all of them unbind, the service is destroyed.

优点:

1. 可以通过AIDL或Messager实现IPC(实际都是通过Binder实现的);

2. 可以实现双向IPC,client可以通过onServiceConnected()取得service的Binder,之后也可以通过Binder将自己的Binde发送r给service,从而实现双向IPC。

混合方式:service can work both ways,it can be started and also allow binding.

onStartCommand()的返回值

Notice that onStartCommand() must return an integer, which describes how the system should re-start the service after it is killed:

START_STICKY:

service will be re-created(onCreate() is called), and system will guarantee onStartCommand() is called, but do not re-deliver the last intent. Instead, the system calls onStartCommand() with a null intent(?个人试验未成功?), unless there were pending intents to start the service.

START_STICKY_COMPATIBILITY

compatibility version of START_STICKY that does not guarantee that onStartCommand() will be called.

START_NOT_STICKY:

service will NOT be re-created unless there are pending intents to the service.

START_REDELIVER_INTENT

service will be re-created, and system will call onStartCommand() with the last intent that was delivered to the service. Any pending intents are delivered in turn.

不得不说的几点:

1. service可以声明为私有。you can declare the service as private in the manifest file by setting the android:exported to "false", and block access from other applications. Only components of the same application or applications with the same user ID can start the service or bind to it. You can also use the permission attribute to limit the external components that can interact with the service).

2. service可以运行在其它进程。Normally, all components of an application run in the default process created for the application. It has the same name as the application‘s package name. The <application> element's android:process attribute can set a different default name for all components. But component can override the default with its own process attribute, allowing you to spread your application across multiple processes.

If the name assigned begins with a colon (':'), a new process, private to the application, is created to run the service.(?个人试验未成功?)

If the name begins with a lowercase, the service will run in a global process of that name.

但是需要注意的是,一旦创建新的进程,不管是unbind还是stopService,即使service已经被destroy,系统也不会kill该进程!

2. AIDL(Android Interface Definition Language )文件中定义的接口会被编译生成对应的java文件,可以看到其中关键的

service启动流程

======== case 1. bind a service ============

TestAidl-Client: ------ =====> bindService()------

TestAidl-Client: ------ <===== bindService()------

TestAidl-Service: ------ service onCreate()------

TestAidl-Service: ------ service onBind()------ :onBind() is only called once, even we call bindService() multiple times, onBind() wont't be invoked.

TestAidl-Client: ------ onServiceConnected()------

======== case 2. unbind a service ============

TestAidl-Client: ------ =====> unbindService()------:if unbindService() is called with an un-bound service, exception will occur : java.lang.IllegalArgumentException: Service not registered

TestAidl-Client: ------ <===== unbindService()------:NOTE: onServiceDisconnected() won't be called due to unbindService(), 只有当servie异常退出时,系统才会调用onServiceDisconnected()

TestAidl-Service: ------ service onUnbind()------:onUnbind() is only called once when the last bound component unbind from the service, usually the service onDestroy() will be called afterwards..

【TestAidl-Service: ------ service onDestroy()------】

======== case 3. start a service ============

TestAidl-Client: ------ =====> startService()------

TestAidl-Client: ------ <===== startService()------

TestAidl-Service: ------ service onCreate()------

TestAidl-Client: ------ service onStartCommand()------:You should never call onStartCommand() directly.

======== case 4. stop a service ============

TestAidl-Client: ------ =====> stopService()------:stopService() can be called multiple times, nothing happened.

TestAidl-Client: ------ <===== stopService()------

【TestAidl-Service: ------ service onDestroy()------】

所以,在Service,只有onStart( )可被多次调用(通过多次startService调用),其他onCreate( ),onBind( ),onUnbind( ),onDestory( )在一个生命周期中只能被调用一次。

service的生命周期

1. A Started service will be destroyed once stopService() is called, no matter which component calls.

2. A bound service will be destroyed only when the last bound component calls the unbindService().

3. if a service is both started and bound, it will be destroyed when stopService() is called and no one is bound to the service at that time,除此之外,不管是调用unbindService()或者stopService()都是不起作用的。

转载于:https://blog.51cto.com/8675042/1731820

android的Service相关推荐

  1. Android中service应用

    Android开发中,当需要创建在后台运行的程序的时候,就要使用到Service.Service 可以分为有无限生命和有限生命两种.特别需要注意的是Service跟Activities是不同的(简单来 ...

  2. android 47 service绑定

    如果一个service已经启动了,activity和service绑定了在解除邦定,则这个service不会销毁,因为这个service不是这个Activity创建的. service生命周期: Ac ...

  3. Android开发--Service和Activity通过广播传递消息

    Android的Service也运行在主线程,但是在服务里面是没法直接调用更改UI,如果需要服务传递消息给Activity,通过广播是其中的一种方法: 一.在服务里面发送广播 通过intent传送数据 ...

  4. android Hander Service 广播的综合使用案例

    android Hander  Service  广播的综合使用案例 原理:在主activity里启动一个服务,这个服务通过Handler每一秒发送一条广播,并在主activity里注册一个广播接受者 ...

  5. Android 通过Service单独进程模仿离线推送 Server Push

    2019独角兽企业重金招聘Python工程师标准>>> 概述: 首先简单阐述一下我对于消息推送的理解,这里拿QQ来举例吧,当我们手机端的QQ离线了,并且退出了QQ应用,但是这时候如果 ...

  6. Android之Service与IntentService的比较

    Android之Service与IntentService的比较  不知道大家有没有和我一样,以前做项目或者练习的时候一直都是用Service来处理后台耗时操作,却很少注意到还有个IntentServ ...

  7. Android 保持Service不被Kill掉的方法--双Service守护 Android实现双进程守护

    本文分为两个部分,第一部分为双Service守护,第二部分为双进程守护 第一部分: 一.Service简介:Java.lang.Object ↳Android.content.Context  ↳an ...

  8. Android之Service

    2019独角兽企业重金招聘Python工程师标准>>> 1.Service的种类   按运行地点分类: 类别 区别  优点 缺点   应用 本地服务(Local) 该服务依附在主进程 ...

  9. Android中Service的使用

    我个人的理解是:我们平时使用的android系统的app的后台应用,就是这个原理 可以利用Service实现程序在后台运行,依照这个原理,可以通过Service来实现关键代码的运行与实现. <一 ...

  10. 关于Android的Service知识点,你知道吗?

    目录 学习Service相关知识点: 概述: Service生命周期: Service的基本用法: 服务. 问:达叔,今日工作累吗? 答:累啊,那么问你,你知道Android中的 Service(服务 ...

最新文章

  1. 对于c语言int类型和float,以及double类型表示范围的计算
  2. java 中方法重载
  3. html语言标记的特点,HTML的特点
  4. m3u8文件在手机上用什么软件看_如何用手机从一个网页下载视频
  5. DeepSORT多目标跟踪算法
  6. 【玩转cocos2d-x之十五】关卡选择的设计
  7. 带有Angular JS的Java EE 7 – CRUD,REST,验证–第2部分
  8. 单例模式及C++实现代码
  9. php redis 队列,Redis 实现队列
  10. keil stm32标准库放在哪里_STM32之PWM
  11. 百度SEO emlog博客lu1.3模板
  12. threadlocal存连接对象的目的_ThreadLocal 介绍
  13. typora工具的使用方法-一款非常适合程序员的工具
  14. Spring如何配置bean属性
  15. 2021-06-16异步调用 CompletableFuture
  16. CS5211替代LT7211B参数特性与优势|DP转LVDS方案
  17. 计算机手机共享上网,电脑建WIFI热点 手机共享上网教程
  18. 在线考试答题系统,操作简单/实用免费/更新无感知
  19. 读明朝那些事儿有感:书生的骨
  20. Rancher部署日志

热门文章

  1. php新建数据表输入自己相信,php学习记录 - whoAmIR的个人空间 - OSCHINA - 中文开源技术交流社区...
  2. quarts集群 运维_精讲Elastic-job + Quartz实现企业级定时任务
  3. java设计一个程序后怎么测试_Java语言程序设计(第1阶段学习测试)(都平)
  4. 理解vue中$watch使用
  5. mysql maratadb_Mysql/Mairadb主从复制
  6. 20190815:(leetcode习题)两数之和(2种方法)
  7. windows10 1903中vmware无法运行解决方法和15.5安装
  8. 关于问题PageNotFound.noHandlerFound No mapping found for HTTP的解决
  9. Android 源码编译过程
  10. 【转】vb 关于commondialog的多选