android编写Service入门

android SDK提供了Service,用于类似*nix守护进程或者windows的服务。

Service有两种类型:

  1. 本地服务(Local Service):用于应用程序内部
  2. 远程服务(Remote Sercie):用于android系统内部的应用程序之间

前者用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。

后者可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。

编写不需和Activity交互的本地服务示例

本地服务编写比较简单。首先,要创建一个Service类,该类继承android的Service类。这里写了一个计数服务的类,每秒钟为计数器加一。在服务类的内部,还创建了一个线程,用于实现后台执行上述业务逻辑。

   1:  package com.easymorse;
   2:   
   3:  import android.app.Service;
   4:  import android.content.Intent;
   5:  import android.os.IBinder;
   6:  import android.util.Log;
   7:   
   8:  public class CountService extends Service {
   9:   
  10:      private boolean threadDisable;
  11:   
  12:      private int count;
  13:   
  14:      @Override
  15:      public IBinder onBind(Intent intent) {
  16:          return null;
  17:      }
  18:   
  19:      @Override
  20:      public void onCreate() {
  21:          super.onCreate();
  22:          new Thread(new Runnable() {
  23:   
  24:              @Override
  25:              public void run() {
  26:                  while (!threadDisable) {
  27:                      try {
  28:                          Thread.sleep(1000);
  29:                      } catch (InterruptedException e) {
  30:                      }
  31:                      count++;
  32:                      Log.v("CountService", "Count is " + count);
  33:                  }
  34:              }
  35:          }).start();
  36:      }
  37:   
  38:      @Override
  39:      public void onDestroy() {
  40:          super.onDestroy();
  41:          this.threadDisable = true;
  42:          Log.v("CountService", "on destroy");
  43:      }
  44:   
  45:      public int getCount() {
  46:          return count;
  47:      }
  48:   
  49:  }

需要将该服务注册到配置文件AndroidManifest.xml中,否则无法找到:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   3:     package="com.easymorse" android:versionCode="1" android:versionName="1.0">
   4:     <application android:icon="@drawable/icon" android:label="@string/app_name">
   5:         <activity android:name=".LocalServiceDemoActivity"
   6:             android:label="@string/app_name">
   7:             <intent-filter>
   8:                 <action android:name="android.intent.action.MAIN" />
   9:                 <category android:name="android.intent.category.LAUNCHER" />
  10:             </intent-filter>
  11:         </activity>
  12:         <service android:name="CountService" />
  13:     </application>
  14:     <uses-sdk android:minSdkVersion="3" />
  15: </manifest> 

在Activity中启动和关闭本地服务。

   1:  package com.easymorse;
   2:   
   3:  import android.app.Activity;
   4:  import android.content.Intent;
   5:  import android.os.Bundle;
   6:   
   7:  public class LocalServiceDemoActivity extends Activity {
   8:      /** Called when the activity is first created. */
   9:      @Override
  10:      public void onCreate(Bundle savedInstanceState) {
  11:          super.onCreate(savedInstanceState);
  12:          setContentView(R.layout.main);
  13:   
  14:          this.startService(new Intent(this, CountService.class));
  15:      }
  16:   
  17:      @Override
  18:      protected void onDestroy() {
  19:          super.onDestroy();
  20:          this.stopService(new Intent(this, CountService.class));
  21:      }
  22:  }

可通过日志查看到后台线程打印的计数内容。

编写本地服务和Activity交互的示例

上面的示例是通过startService和stopService启动关闭服务的。适用于服务和activity之间没有调用交互的情况。如果之间需要传递参数或者方法调用。需要使用bind和unbind方法。

具体做法是,服务类需要增加接口,比如ICountService,另外,服务类需要有一个内部类,这样可以方便访问外部类的封装数据,这个内部类需要继承Binder类并实现ICountService接口。还有,就是要实现Service的onBind方法,不能只传回一个null了。

这是新建立的接口代码:

   1:  package com.easymorse;
   2:   
   3:  public interface ICountService {
   4:   
   5:      public abstract int getCount();
   6:  }
   7:  修改后的CountService代码:
   8:   
   9:  package com.easymorse;
  10:   
  11:  import android.app.Service;
  12:  import android.content.Intent;
  13:  import android.os.Binder;
  14:  import android.os.IBinder;
  15:  import android.util.Log;
  16:   
  17:  public class CountService extends Service implements ICountService {
  18:   
  19:      private boolean threadDisable;
  20:   
  21:      private int count;
  22:   
  23:      private ServiceBinder serviceBinder=new ServiceBinder();
  24:   
  25:      public class ServiceBinder extends Binder implements ICountService{
  26:          @Override
  27:          public int getCount() {
  28:              return count;
  29:          }
  30:      }
  31:   
  32:      @Override
  33:      public IBinder onBind(Intent intent) {
  34:          return serviceBinder;
  35:      }
  36:   
  37:      @Override
  38:      public void onCreate() {
  39:          super.onCreate();
  40:          new Thread(new Runnable() {
  41:   
  42:              @Override
  43:              public void run() {
  44:                  while (!threadDisable) {
  45:                      try {
  46:                          Thread.sleep(1000);
  47:                      } catch (InterruptedException e) {
  48:                      }
  49:                      count++;
  50:                      Log.v("CountService", "Count is " + count);
  51:                  }
  52:              }
  53:          }).start();
  54:      }
  55:   
  56:      @Override
  57:      public void onDestroy() {
  58:          super.onDestroy();
  59:          this.threadDisable = true;
  60:          Log.v("CountService", "on destroy");
  61:      }
  62:   
  63:      /* (non-Javadoc)
  64:       * @see com.easymorse.ICountService#getCount()
  65:       */
  66:      public int getCount() {
  67:          return count;
  68:      }
  69:   
  70:  }

服务的注册也要做改动,AndroidManifest.xml文件:

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

Acitity代码不再通过startSerivce和stopService启动关闭服务,另外,需要通过ServiceConnection的内部类实现来连接Service和Activity。

   1:  package com.easymorse;
   2:   
   3:  import android.app.Activity;
   4:  import android.content.ComponentName;
   5:  import android.content.Intent;
   6:  import android.content.ServiceConnection;
   7:  import android.os.Bundle;
   8:  import android.os.IBinder;
   9:  import android.util.Log;
  10:   
  11:  public class LocalServiceDemoActivity extends Activity {
  12:   
  13:      private ServiceConnection serviceConnection = new ServiceConnection() {
  14:   
  15:          @Override
  16:          public void onServiceConnected(ComponentName name, IBinder service) {
  17:              countService = (ICountService) service;
  18:              Log.v("CountService", "on serivce connected, count is "
  19:                      + countService.getCount());
  20:          }
  21:   
  22:          @Override
  23:          public void onServiceDisconnected(ComponentName name) {
  24:              countService = null;
  25:          }
  26:   
  27:      };
  28:   
  29:      private ICountService countService;
  30:   
  31:      /** Called when the activity is first created. */
  32:      @Override
  33:      public void onCreate(Bundle savedInstanceState) {
  34:          super.onCreate(savedInstanceState);
  35:          setContentView(R.layout.main);
  36:          this.bindService(new Intent("com.easymorse.CountService"),
  37:                  this.serviceConnection, BIND_AUTO_CREATE);
  38:      }
  39:   
  40:      @Override
  41:      protected void onDestroy() {
  42:          super.onDestroy();
  43:          this.unbindService(serviceConnection);
  44:      }
  45:  }
编写传递基本型数据的远程服务

上面的示例,可以扩展为,让其他应用程序复用该服务。这样的服务叫远程(remote)服务,实际上是进程间通信(RPC)。

这时需要使用android接口描述语言(AIDL)来定义远程服务的接口,而不是上述那样简单的java接口。扩展名为aidl而不是java。可用上面的ICountService改动而成ICountSerivde.aidl,eclipse会自动生成相关的java文件。

package com.easymorse; interface ICountService { int getCount(); }

编写服务(Service)类,稍有差别,主要在binder是通过远程获得的,需要通过桩(Stub)来获取。桩对象是远程对象的本地代理。

   1:  package com.easymorse;
   2:   
   3:  import android.app.Service;
   4:  import android.content.Intent;
   5:  import android.os.IBinder;
   6:  import android.os.RemoteException;
   7:  import android.util.Log;
   8:   
   9:  public class CountService extends Service {
  10:   
  11:      private boolean threadDisable;
  12:   
  13:      private int count;
  14:   
  15:      private ICountService.Stub serviceBinder = new ICountService.Stub() {
  16:   
  17:          @Override
  18:          public int getCount() throws RemoteException {
  19:              return count;
  20:          }
  21:      };
  22:   
  23:      @Override
  24:      public IBinder onBind(Intent intent) {
  25:          return serviceBinder;
  26:      }
  27:   
  28:      @Override
  29:      public void onCreate() {
  30:          super.onCreate();
  31:          new Thread(new Runnable() {
  32:   
  33:              @Override
  34:              public void run() {
  35:                  while (!threadDisable) {
  36:                      try {
  37:                          Thread.sleep(1000);
  38:                      } catch (InterruptedException e) {
  39:                      }
  40:                      count++;
  41:                      Log.v("CountService", "Count is " + count);
  42:                  }
  43:              }
  44:          }).start();
  45:      }
  46:   
  47:      @Override
  48:      public void onDestroy() {
  49:          super.onDestroy();
  50:          this.threadDisable = true;
  51:          Log.v("CountService", "on destroy");
  52:      }
  53:  }

配置文件AndroidManifest.xml和上面的类似,没有区别。

在Activity中使用服务的差别不大,只需要对ServiceConnection中的调用远程服务的方法时,要捕获异常。

   1:  private ServiceConnection serviceConnection = new ServiceConnection() {
   2:   
   3:      @Override
   4:      public void onServiceConnected(ComponentName name, IBinder service) {
   5:          countService = (ICountService) service;
   6:          try {
   7:              Log.v("CountService", "on serivce connected, count is "
   8:                      + countService.getCount());
   9:          } catch (RemoteException e) {
  10:              throw new RuntimeException(e);
  11:          }
  12:      }
  13:   
  14:      @Override
  15:      public void onServiceDisconnected(ComponentName name) {
  16:          countService = null;
  17:      }
  18:   
  19:  };
这样就可以在同一个应用程序中使用远程服务的方式和自己定义的服务交互了。

如果是另外的应用程序使用远程服务,需要做的是复制上面的aidl文件和相应的包构到应用程序中,其他调用等都一样。

编写传递复杂数据类型的远程服务

远程服务往往不只是传递java基本数据类型。这时需要注意android的一些限制和规定:

  1. android支持String和CharSequence
  2. 如果需要在aidl中使用其他aidl接口类型,需要import,即使是在相同包结构下;
  3. android允许传递实现Parcelable接口的类,需要import;
  4. android支持集合接口类型List和Map,但是有一些限制,元素必须是基本型或者上述三种情况,不需要import集合接口类,但是需要对元素涉及到的类型import;
  5. 非基本数据类型,也不是String和CharSequence类型的,需要有方向指示,包括in、out和inout,in表示由客户端设置,out表示由服务端设置,inout是两者均可设置。

这里将前面的例子中返回的int数据改为复杂数据类型:

   1:  package com.easymorse;
   2:   
   3:  import android.os.Parcel;
   4:  import android.os.Parcelable;
   5:   
   6:  public class CountBean implements Parcelable {
   7:   
   8:      public static final Parcelable.Creator<CountBean> CREATOR = new Creator<CountBean>() {
   9:   
  10:          @Override
  11:          public CountBean createFromParcel(Parcel source) {
  12:              CountBean bean = new CountBean();
  13:              bean.count = source.readInt();
  14:              return bean;
  15:          }
  16:   
  17:          @Override
  18:          public CountBean[] newArray(int size) {
  19:              return new CountBean[size];
  20:          }
  21:   
  22:      };
  23:   
  24:      public int count;
  25:   
  26:      @Override
  27:      public void writeToParcel(Parcel dest, int flags) {
  28:          dest.writeInt(this.count);
  29:      }
  30:   
  31:      @Override
  32:      public int describeContents() {
  33:          return 0;
  34:      }
  35:   
  36:  }
然后,需要在相同包下建一个同名的aidl文件,用于android生成相应的辅助文件:

package com.easymorse; parcelable CountBean;

这一步是android 1.5后的变化,无法通过adt生成aidl,也不能用一个比如全局的project.aidl文件,具体见:

http://www.anddev.org/viewtopic.php?p=20991

然后,需要在服务的aidl文件中修改如下:

package com.easymorse; import com.easymorse.CountBean; interface ICountService { CountBean getCount(); }

其他的改动很小,只需将CountService和调用CountService的部分修改为使用CountBean即可。

原文地址:https://www.cnblogs.com/GnagWang/p/1891617.html