Android中Service的使用详解和注意点(LocalService)

来源:互联网 发布:淘宝退款假冒品牌 编辑:程序博客网 时间:2024/05/29 17:51


开始,先稍稍讲一点android中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 与 Thread 的区别

很多时候,你可能会问,为什么要用 Service,而不用 Thread 呢,因为用 Thread 是很方便的,比起 Service 也方便多了,下面我详细的来解释一下。

1). Thread:Thread 是程序执行的最小单元,它是分配CPU的基本单位。可以用 Thread 来执行一些异步的操作。

2). Service:Service 是android的一种机制,当它运行的时候如果是Local Service,那么对应的 Service 是运行在主进程的 main 线程上的。如:onCreate,onStart 这些函数在被系统调用的时候都是在主进程的 main 线程上运行的。如果是Remote Service,那么对应的 Service 则是运行在独立进程的 main 线程上。因此请不要把 Service 理解成线程,它跟线程半毛钱的关系都没有!

既然这样,那么我们为什么要用 Service 呢?其实这跟 android 的系统机制有关,我们先拿 Thread 来说。Thread 的运行是独立于 Activity 的,也就是说当一个 Activity 被 finish 之后,如果你没有主动停止 Thread 或者 Thread 里的 run 方法没有执行完毕的话,Thread 也会一直执行。因此这里会出现一个问题:当 Activity 被 finish 之后,你不再持有该 Thread 的引用。另一方面,你没有办法在不同的 Activity 中对同一 Thread 进行控制。

举个例子:如果你的 Thread 需要不停地隔一段时间就要连接服务器做某种同步的话,该 Thread 需要在 Activity 没有start的时候也在运行。这个时候当你 start 一个 Activity 就没有办法在该 Activity 里面控制之前创建的 Thread。因此你便需要创建并启动一个 Service ,在 Service 里面创建、运行并控制该 Thread,这样便解决了该问题(因为任何 Activity 都可以控制同一 Service,而系统也只会创建一个对应 Service 的实例)。

  

因此你可以把 Service 想象成一种消息服务,而你可以在任何有 Context 的地方调用 Context.startService、Context.stopService、Context.bindService,Context.unbindService,来控制它,你也可以在 Service 里注册 BroadcastReceiver,在其他地方通过发送 broadcast 来控制它,当然这些都是 Thread 做不到的。

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。


下面开始上一个很简单的代码哈~里头的注释也要注意哦,有在上面没有讲到的会在注释里提到哇(尤其适用Bind方法的时候的数据传输哇)~

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

    <?xml version="1.0" encoding="utf-8"?>      <manifest xmlns:android="http://schemas.android.com/apk/res/android"          package="com.test.localservice" android:versionCode="1"          android:versionName="1.0">          <uses-sdk android:minSdkVersion="8" />                <application android:icon="@drawable/icon" android:label="@string/app_name">              <activity android:name=".LocalServiceTestActivity"                  android:label="@string/app_name">                  <intent-filter>                      <action android:name="android.intent.action.MAIN" />                      <category android:name="android.intent.category.LAUNCHER" />                  </intent-filter>              </activity>              <service android:name=".MyService">                  <intent-filter>                      <action android:name="com.test.SERVICE_TEST" />                      <category android:name="android.intent.category.default" />                  </intent-filter>              </service>          </application>      </manifest>  

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

    package com.test.service;            import android.app.Service;      import android.content.Intent;      import android.os.Binder;      import android.os.IBinder;      import android.util.Log;            public class MyService extends Service {                public class LocalBinder extends Binder {              String stringToSend = "I'm the test String";              MyService getService() {                  Log.i("TAG", "getService ---> " + MyService.this);                  return MyService.this;              }          }                private final IBinder mBinder = new LocalBinder();                @Override          public IBinder onBind(Intent intent) {              // TODO Auto-generated method stub              Log.i("TAG", "onBind~~~~~~~~~~~~");      //      IBinder myIBinder = null;      //      if ( null == myIBinder )       //          myIBinder = new LocalBinder() ;       //      return myIBinder;              return mBinder;     //也可以像上面几个语句那样重新new一个IBinder              //如果这边不返回一个IBinder的接口实例,那么ServiceConnection中的onServiceConnected就不会被调用              //那么bind所具有的传递数据的功能也就体现不出来~\(≧▽≦)/~啦啦啦(这个返回值是被作为onServiceConnected中的第二个参数的)          }                @Override          public void onCreate() {              // TODO Auto-generated method stub              super.onCreate();                    Log.i("TAG", "onCreate~~~~~~~~~~");          }                @Override          public void onDestroy() {              // TODO Auto-generated method stub              super.onDestroy();              Log.i("TAG", "onDestroy~~~~~~~~~~~");          }                @Override          public void onStart(Intent intent, int startId) {              // TODO Auto-generated method stub              super.onStart(intent, startId);              Log.i("TAG", "onStart~~~~~~");          }                @Override          public int onStartCommand(Intent intent, int flags, int startId) {              // TODO Auto-generated method stub              Log.i("TAG", "onStartCommand~~~~~~~~~~~~");              return super.onStartCommand(intent, flags, startId);          }                @Override          public boolean onUnbind(Intent intent) {              // TODO Auto-generated method stub              Log.i("TAG", "onUnbind~~~~~~~~~~~~~~~~");              return super.onUnbind(intent);          }      }  

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

package com.test.service;    import android.app.Activity;  import android.content.ComponentName;  import android.content.Context;  import android.content.Intent;  import android.content.ServiceConnection;  import android.media.MediaPlayer;  import android.os.Bundle;  import android.os.IBinder;  import android.util.Log;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;    public class ServiceTestActivity extends Activity {      private Button startButton, bindButton;      private Button stopButton, unbindButton;      private ServiceConnection sc;      private MediaPlayer mediaPlayer = null;      private MyService myService;// 类似于MediaPlayer mPlayer = new                                  // MediaPlayer();只不过这边的服务是自定义的,不是系统提供好了的        /** Called when the activity is first created. */      @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);            startButton = (Button) findViewById(R.id.startbutton_id);          stopButton = (Button) findViewById(R.id.stopbutton_id);          bindButton = (Button) findViewById(R.id.bindbutton_id);          unbindButton = (Button) findViewById(R.id.unbindbutton_id);            sc = new ServiceConnection() {              /*              * 只有在MyService中的onBind方法中返回一个IBinder实例才会在Bind的时候              * 调用onServiceConnection回调方法              * 第二个参数service就是MyService中onBind方法return的那个IBinder实例,可以利用这个来传递数据              */              @Override              public void onServiceConnected(ComponentName name, IBinder service) {                  // TODO Auto-generated method stub                  myService = ((MyService.LocalBinder) service).getService();                  String recStr = ((MyService.LocalBinder) service).stringToSend;                  //利用IBinder对象传递过来的字符串数据(其他数据也可以啦,哪怕是一个对象也OK~~)                  Log.i("TAG","The String is : " + recStr);                  Log.i("TAG", "onServiceConnected : myService ---> " + myService);              }                @Override              public void onServiceDisconnected(ComponentName name) {                  /* SDK上是这么说的:                  * This is called when the connection with the service has been unexpectedly disconnected                  * that is, its process crashed. Because it is running in our same process, we should never see this happen.                  * 所以说,只有在service因异常而断开连接的时候,这个方法才会用到*/                  // TODO Auto-generated method stub                  sc = null;                  Log.i("TAG", "onServiceDisconnected : ServiceConnection --->"                          + sc);              }            };          startButton.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  Intent intent = new Intent(ServiceTestActivity.this,                          MyService.class);                  startService(intent);                  Log.i("TAG", "Start button clicked");              }          });            stopButton.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                    /*                  * Intent intent = new                  * Intent(LocalServiceTestActivity.this,MyService.class);                  * stopService(intent); 这种方法也是可以的哈~                  */                    Intent intent = new Intent();                  intent.setAction("com.test.SERVICE_TEST");                  stopService(intent);                  Log.i("TAG", "Stop Button clicked");              }          });            bindButton.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub  //              Intent intent = new Intent(LocalServiceTestActivity.this,  //                      MyService.class);//这样也可以的                  Intent intent = new Intent();                  intent.setAction("com.test.SERVICE_TEST");                  bindService(intent, sc, Context.BIND_AUTO_CREATE);//bind多次也只会调用一次onBind方法                  Log.i("TAG", "Bind button clicked");              }          });            unbindButton.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  unbindService(sc);                  // 这边如果重复unBind会报错,提示该服务没有注册的错误——IllegalArgumentException:                  // Service not registered: null                  // 所以一般会设置一个flag去看这个service                  // bind后有没有被unBind过,没有unBind过才能调用unBind方法(这边我就不设置了哈~\(≧▽≦)/~啦啦啦)                  Log.i("TAG", "Unbind Button clicked");              }          });      }  }


转自:http://blog.csdn.net/listening_music/article/details/6927988
0 0
原创粉丝点击