先唠叨两句以我心中郁闷:今天寝室上午断电,下午去充了钱,吃完晚饭我去刷电卡,可是刷不出来,叫了三个人来刷都没一个人能刷出来,这叫我们晚上怎么过!我自己的是台式机,现在用的是同寝的笔记本,他们三个都考研,可是这个笔记本的键盘太TM难用了!

好吧,先心平气和一下,开始今天的Android的四大组件之一Service的学习

先说明一下,我用的这台笔记本没android的环境,没法演示,说实话就算有,我也不太想用这个,太慢了,因为我习惯自己那个4G的内存,用别的都有甩键盘的冲动(这个键盘甩不起来).

先打开文档:



1,什么是Service(服务)

这里我觉得有必要和Activity进行比较,Service是可以在后台执行长时间运行的操作,而且没有图形用户界面的这样一个应用程序组件.另一个应用程序组件可以启动一个Service,并会继续在后台运行,即使用户选择了另外一个应用程序.此外,一个组件可以绑定一个服务与他交互,甚至进行进程间通信.

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC)

Service的特点:

1,Service运行于后台,没有UI

2,用户切换程序的时候,Service不会暂停或停止

3,Service可以被绑定,能进行IPC(进程间通信)


(以上是我个人按照文档里的说明稍微总结的一些东西,仅供参考)

2,如何启动Service

启动Service有两种方式:

1,一个应用程序组件调用startService(),简称Started,需要在定义这个Service的类中覆写回调函数onStartCommand()

2,一个应用程序组件调用bindService(),简称Bound,需要在定义个Service的类中覆写回调函数onBind()

两种方式特点不一:

Started方式:一个应用组件(比如Activity)启动了Service后,Service可以无限期的运行,即使启动他的这个组件被销毁了,他也可以依然存在,如果要停止Service,就需要在这个组件被销毁前在某个方法里调用Context.stopService()或者stopSelf().通常一个Service只完成一个操作,而且不会返回结果给调用者.

Bound方式:绑定了的Service会提供了一个客户端接口,允许组件与Service进行交互,甚至进行进程间通信.绑定Service存在的条件是:要有另外一个或多个应用程序组件绑定他,当Service没有被任何组件绑定的时候,这个Service就被销毁了.

StartedA service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.BoundA service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

一个Service既能以Started的方式启动也能同时以Bound的方式启动.只要覆写了Service onStartCommand()和onBind()方法.

一个service只要启动了(不管以什么方式启动),任何应用程序都能通过使用一个Intent(意图)来调用他.Service也可以通过设置不被其他程序所调用,具体方法是在manifest文件里将Service声明为private(私有的).


文档里有一个提醒:

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

主要是关于线程的问题,是说:一个Service是运行在其宿主进程的主线程中,它本身不能创建他自己的线程也不能运行在单独的进程中(除非另行指定),意味着在某些时候,我们需要一个单独线程或一个单独的进程来执行我们的Service.用一个单独的线程来执行Service的好处是可以减少ANR(应用程序无响应)错误,主线程也可以更好地致力于用户界面的Acitvities.


3, Service类的一些方法

先找到Service这个类,大致浏览一下:



Service类里有一些方法,API里写得很详细:



那么创建一个Service需要覆写一些重要的方法,前面已经提到过得onStartCommand()和onBind(),还有这个onCreate()和onDestory(),

如果看过我之前写过的关于Activity的概述,很容易就知道这些方法很多都是与Service的生命周期(lifecycle)有关,




先看个图,我自己都快搞不清状况了

这个是Service的生命周期



从图上可知onCreate()方法是第一调用的方法,如果这个Service已经在运行中,onCreate()方法不会被调用

onDestory()方法是在Service被销毁要调用的方法,这个方法要做的事主要还是收尾工作,清理资源.

关于Service的生命周期,我真的不想再说什么了,这个图将得太清晰了,如果你觉得还不是很理解,可以参考Activity的生命周期,不过待会Bound Service的生命周期我觉得还是有必要详细说一下

4,声明Service

声明一个Service当然是在manifest配置文件里,把文档里的例子copy过来:

<manifest ... >  ...  <application ... >      <service android:name=".ExampleService" />      ...  </application></manifest>
这个文件没什么好说的,就是这么配置

5,创建一个Started Service

文档里提供了两个类供我们选择进行继承:

1,Service,继承Service最好要自己创建一个新的线程来进行所需的操作,因为默认Service是运行调用Service的应用程序的主线程里的,这样明显会减慢应用程序的性能

2,IntentService ,Service的子类,可以用一个工作线程一次处理一个请求,直到处理完成,继承IntentService 只需要实现onHandleIntent()方法,这个方法是用来接受每次请求的Intent(意图).

建议是之间继承IntentService,理由:

Because most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using the IntentService class
因为大多数Started Service不需要处理多个请求


扩展IntentService的步骤是:

还是用个例子说明:


public class HelloIntentService extends IntentService {  /**    * A constructor is required, and must call the super IntentService(String)   * constructor with a name for the worker thread.   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   * The IntentService calls this method from the default worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }}

很简单:1,有个无参构造 2,覆写onHandleIntent()方法

为什么这么简单方便呢?因为IntentService已经把大部分的工作都做了


当需要处理多线程的时候,我们的Service还是需要继承Service

扩展Service的步骤:



未完!先回自己寝室一下


更多相关文章

  1. 实现ListView的条目下自动隐藏显示Button的方法
  2. Android中获取后台正在运行的应用列表(附源码)
  3. 为Android的apk应用程序文件加壳以防止反编译的教程
  4. 6 个可以让代码变得更整洁的 Android(安卓)库
  5. Android(安卓)模块化、组件化、插件化及热修复,大集结篇。
  6. 第三章:Creating Applications and activities-(八)深入了解Andro
  7. Android之App界面的挂载与显示及源码分析
  8. android开发游记:性能测试中内存泄露排查方法与防止泄露编码心得
  9. Android关于第三方h5在webview调用摄像头及相机的处理

随机推荐

  1. Android 读取doc文件
  2. 【Arcgis android】 离线编辑实现及一些
  3. Android:TextSwitcher、imageSwitcher
  4. Android一些网站介绍
  5. Android中,把XML文件转换成Object对象的方
  6. android ndk编译getevent
  7. Android(安卓)MediaCodec踩坑笔记
  8. Android开发利器之Data Binding Compiler
  9. Android应用程序组件Content Provider在
  10. android SQLite操作