大家好,上一节我讲解了Android Activity的生命周期,这一节我将讲解一下Service,首先我们要知道Service具体是干什么的,什么时候用到?以及它的生命周期等。

Service概念及用途:

Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,那 我们什么时候会用到Service呢?比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我 们就听不到歌了,所以这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以 用Service在后台定时更新,而不用每打开应用的时候在去获取。

Service生命周期 :

Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我 们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法,具体的可以看下面的实例。

Service与Activity通信:

Service后端的数据最终还是要呈现在前端Activity之上的,因为启动Service时,系统会重新开启一个新 的进程,这就涉及到不同进程间通信的问题了(AIDL)这一节我不作过多描述,当我们想获取启动的Service实例时,我们可以用到 bindService和onBindService方法,它们分别执行了Service中IBinder()和onUnbind()方法。

为了让大家 更容易理解,我写了一个简单的Demo,大家可以模仿着我,一步一步的来。

第一步:新建一个Android工程,我这里命名为ServiceDemo.

第二步:修改main.xml代码,我这里增加了四个按钮,代码如下:

view plain copy to clipboard print ?
  1. <?xml version= "1.0"  encoding= "utf-8" ?>  
  2. "http://schemas.android.com/apk/res/android"   
  3.     android:orientation="vertical"   
  4.     android:layout_width="fill_parent"   
  5.     android:layout_height="fill_parent"   
  6.     >  
  7.     
  8.         android:id="@+id/text"     
  9.         android:layout_width="fill_parent"    
  10.         android:layout_height="wrap_content"    
  11.         android:text="@string/hello"   
  12.         />  
  13.     
  14.         android:id="@+id/startservice"   
  15.         android:layout_width="fill_parent"   
  16.         android:layout_height="wrap_content"   
  17.         android:text="startService"   
  18.     />  
  19.     
  20.         android:id="@+id/stopservice"   
  21.         android:layout_width="fill_parent"   
  22.         android:layout_height="wrap_content"   
  23.         android:text="stopService"   
  24.     />  
  25.     
  26.         android:id="@+id/bindservice"   
  27.         android:layout_width="fill_parent"   
  28.         android:layout_height="wrap_content"   
  29.         android:text="bindService"   
  30.     />  
  31.     
  32.         android:id="@+id/unbindservice"   
  33.         android:layout_width="fill_parent"   
  34.         android:layout_height="wrap_content"   
  35.         android:text="unbindService"   
  36.     />  
  37.   
<?xml version="1.0" encoding="utf-8"?>