Android中Service 使用详解(LocalService + RemoteService)

Service 简介:

Service分为本地服务(LocalService)和远程服务(RemoteService):

1、本地服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外Local服务因为是在同一进程因此不需要IPC,也不需要AIDL。相应bindService会方便很多。主进程被Kill后,服务便会终止。

2、远程服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在Activity所在进程被Kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性。该服务是独立的进程,会占用一定资源,并且使用AIDL进行IPC稍微麻烦一点。

按使用方式可以分为以下三种:

1、startService 启动的服务:主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService;

2、bindService 启动的服务:该方法启动的服务可以进行通信。停止服务使用unbindService;

3、startService 同时也 bindService 启动的服务:停止服务应同时使用stepService与unbindService

 

 

Service的生命周期

onCreate -- onStart -- onDestroy -- onBind 

1). 被启动的服务的生命周期:如果一个Service被某个Activity 调用 Context.startService 方法启动,那么不管是否有Activity使用bindService绑定或unbindService解除绑定到该Service,该Service都在后台运行。如果一个Service被startService 方法多次启动,那么onCreate方法只会调用一次,onStart将会被调用多次(对应调用startService的次数),并且系统只会创建Service的一个实例(因此你应该知道只需要一次stopService调用)。该Service将会一直在后台运行,而不管对应程序的Activity是否在运行,直到被调用stopService,或自身的stopSelf方法。当然如果系统资源不足,android系统也可能结束服务。

 

2). 被绑定的服务的生命周期:如果一个Service被某个Activity 调用 Context.bindService 方法绑定启动,不管调用 bindService 调用几次,onCreate方法都只会调用一次,同时onStart方法始终不会被调用。当连接建立之后,Service将会一直运行,除非调用Context.unbindService 断开连接或者之前调用bindService 的 Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy将被调用。

 

3). 被启动又被绑定的服务的生命周期:如果一个Service又被启动又被绑定,则该Service将会一直在后台运行。并且不管如何调用,onCreate始终只会调用一次,对应startService调用多少次,Service的onStart便会调用多少次。调用unbindService将不会停止Service,而必须调用 stopService 或 Service的 stopSelf 来停止服务。

4). 当服务被停止时清除服务:当一个Service被终止(1、调用stopService;2、调用stopSelf;3、不再有绑定的连接(没有被启动))时,onDestroy方法将会被调用,在这里你应当做一些清除工作,如停止在Service中创建并运行的线程。

 

特别注意:

1、你应当知道在调用 bindService 绑定到Service的时候,你就应当保证在某处调用 unbindService 解除绑定(尽管 Activity 被 finish 的时候绑定会自      动解除,并且Service会自动停止);

2、你应当注意 使用 startService 启动服务之后,一定要使用 stopService停止服务,不管你是否使用bindService; 

3、同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用,才能终止 Service,不管 startService 与 bindService 的调用顺序,如果先调用 unbindService 此时服务不会自动终止,再调用 stopService 之后服务才会停止,如果先调用 stopService 此时服务也不会终止,而再调用 unbindService 或者 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候)之后服务才会自动停止;

4、当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 Activity 如果会自动旋转的话,旋转其实是 Activity 的重新创建,因此旋转之前的使用 bindService 建立的连接便会断开(Context 不存在了),对应服务的生命周期与上述相同。

5、在 sdk 2.0 及其以后的版本中,对应的 onStart 已经被否决变为了 onStartCommand,不过之前的 onStart 任然有效。这意味着,如果你开发的应用程序用的 sdk 为 2.0 及其以后的版本,那么你应当使用 onStartCommand 而不是 onStart。

 

Android中Thread和Service的区别zz - petercao - 博客园
http://www.cnblogs.com/bluestorm/p/5704264.html

 

LocalService代码示例:

首先,因为要再Manifest文件里对服务进行注册,所以就先来Manifest的代码吧~

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.test.localservice" android:versionCode="1"  
  4.     android:versionName="1.0">  
  5.     <uses-sdk android:minSdkVersion="8" />  
  6.   
  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  8.         <activity android:name=".LocalServiceTestActivity"  
  9.             android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.         <service android:name=".MyService">  
  16.             <intent-filter>  
  17.                 <action android:name="com.test.SERVICE_TEST" />  
  18.                 <category android:name="android.intent.category.default" />  
  19.             </intent-filter>  
  20.         </service>  
  21.     </application>  
  22. </manifest>  


然后然后,是服务实现类~

  1. package com.test.service;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.util.Log;  
  8.   
  9. public class MyService extends Service {  
  10.   
  11.     public class LocalBinder extends Binder {  
  12.         String stringToSend = "I'm the test String";  
  13.         MyService getService() {  
  14.             Log.i("TAG", "getService ---> " + MyService.this);  
  15.             return MyService.this;  
  16.         }  
  17.     }  
  18.   
  19.     private final IBinder mBinder = new LocalBinder();  
  20.   
  21.     @Override  
  22.     public IBinder onBind(Intent intent) {  
  23.           
  24.         Log.i("TAG", "onBind~~~~~~~~~~~~");  
  25.   
  26.         return mBinder;       
  27.          
  28.     }  
  29.   
  30.     @Override  
  31.     public void onCreate() {  
  32.           
  33.         super.onCreate();  
  34.   
  35.         Log.i("TAG", "onCreate~~~~~~~~~~");  
  36.     }  
  37.   
  38.     @Override  
  39.     public void onDestroy() {  
  40.           
  41.         super.onDestroy();  
  42.         Log.i("TAG", "onDestroy~~~~~~~~~~~");  
  43.     }  
  44.   
  45.     @Override  
  46.     public void onStart(Intent intent, int startId) {  
  47.           
  48.         super.onStart(intent, startId);  
  49.         Log.i("TAG", "onStart~~~~~~");  
  50.     }  
  51.   
  52.     @Override  
  53.     public int onStartCommand(Intent intent, int flags, int startId) {  
  54.           
  55.         Log.i("TAG", "onStartCommand~~~~~~~~~~~~");  
  56.         return super.onStartCommand(intent, flags, startId);  
  57.     }  
  58.   
  59.     @Override  
  60.     public boolean onUnbind(Intent intent) {  
  61.           
  62.         Log.i("TAG", "onUnbind~~~~~~~~~~~~~~~~");  
  63.         return super.onUnbind(intent);  
  64.     }  
  65. }  

再来,就是我们的Activity的测试类啦~

    1. <pre name="code" class="java">package com.test.service;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.ComponentName;  
    5. import android.content.Context;  
    6. import android.content.Intent;  
    7. import android.content.ServiceConnection;  
    8. import android.media.MediaPlayer;  
    9. import android.os.Bundle;  
    10. import android.os.IBinder;  
    11. import android.util.Log;  
    12. import android.view.View;  
    13. import android.view.View.OnClickListener;  
    14. import android.widget.Button;  
    15.   
    16. public class ServiceTestActivity extends Activity {  
    17.     private Button startButton, bindButton;  
    18.     private Button stopButton, unbindButton;  
    19.     private ServiceConnection sc;  
    20.     private MediaPlayer mediaPlayer = null;  
    21.     private MyService myService;  
    22.       
    23.     @Override  
    24.     public void onCreate(Bundle savedInstanceState) {  
    25.         super.onCreate(savedInstanceState);  
    26.         setContentView(R.layout.main);  
    27.   
    28.         startButton = (Button) findViewById(R.id.startbutton_id);  
    29.         stopButton = (Button) findViewById(R.id.stopbutton_id);  
    30.         bindButton = (Button) findViewById(R.id.bindbutton_id);  
    31.         unbindButton = (Button) findViewById(R.id.unbindbutton_id);  
    32.   
    33.         sc = new ServiceConnection() {  
    34.   
    35.             @Override  
    36.             public void onServiceConnected(ComponentName name, IBinder service) {  
    37.                   
    38.                 myService = ((MyService.LocalBinder) service).getService();  
    39.                 String recStr = ((MyService.LocalBinder) service).stringToSend;  
    40.                   
    41.                 Log.i("TAG","The String is : " + recStr);  
    42.                 Log.i("TAG", "onServiceConnected : myService ---> " + myService);  
    43.             }  
    44.   
    45.             @Override  
    46.             public void onServiceDisconnected(ComponentName name) {  
    47.   
    48.                   
    49.                 sc = null;  
    50.                 Log.i("TAG", "onServiceDisconnected : ServiceConnection --->"  
    51.                         + sc);  
    52.             }  
    53.   
    54.         };  
    55.         startButton.setOnClickListener(new OnClickListener() {  
    56.   
    57.             @Override  
    58.             public void onClick(View v) {  
    59.                   
    60.                 Intent intent = new Intent(ServiceTestActivity.this,  
    61.                         MyService.class);  
    62.                 startService(intent);  
    63.                 Log.i("TAG", "Start button clicked");  
    64.             }  
    65.         });  
    66.   
    67.         stopButton.setOnClickListener(new OnClickListener() {  
    68.   
    69.             @Override  
    70.             public void onClick(View v) {  
    71.                   
    72.   
    73.   
    74.   
    75.                 Intent intent = new Intent();  
    76.                 intent.setAction("com.test.SERVICE_TEST");  
    77.                 stopService(intent);  
    78.                 Log.i("TAG", "Stop Button clicked");  
    79.             }  
    80.         });  
    81.   
    82.         bindButton.setOnClickListener(new OnClickListener() {  
    83.   
    84.             @Override  
    85.             public void onClick(View v) {  
    86.                   
    87.   
    88.   
    89.                 Intent intent = new Intent();  
    90.                 intent.setAction("com.test.SERVICE_TEST");  
    91.                 bindService(intent, sc, Context.BIND_AUTO_CREATE);  
    92.                 Log.i("TAG", "Bind button clicked");  
    93.             }  
    94.         });  
    95.   
    96.         unbindButton.setOnClickListener(new OnClickListener() {  
    97.   
    98.             @Override  
    99.             public void onClick(View v) {  
    100.                   
    101.                 unbindService(sc);  
    102.                   
    103.                   
    104.                   
    105.                   
    106.                 Log.i("TAG", "Unbind Button clicked");  
    107.             }  
    108.         });  
    109.     }  
    110. }
posted @ 2016-07-27 19:47  petercao  阅读(1554)  评论(0编辑  收藏  举报