Android菜鸟的成长笔记(21)——跨进程调用Service

来源:互联网 发布:gamemaker mac 编辑:程序博客网 时间:2024/05/16 13:43

我们都知道在Android中的每一个应用是一个进程,其实每一个应用就相当于Linux系统里面的一个用户,进程和进程之间的通信其实就相当于用户和用户之间的通信,为了实现这种跨进程通信,Android提供了AIDL Service ( Android Interface definition language).

与邦等本地Service不同的是,本地Service的onBind()方法会直接把IBinder对象本身传给客户端的ServiceConnection的onServiceConnected方法的第二个参数。但远程Service的onBind()方法只是将IBinder对象的代理传给客户端的ServiceConnection的onService Connected方法的第二个参数。

ALDL定义的特点:

1、AIDL定义接口的源码必须以.aidl结尾。

2、AIDL接口中用到数据类型,除了基本类型、String、List、Map、CharSequence之外,其他类型全部都需要导包,即使它们在同一个包中也需要导包。

下面来具体实现一个示例:

(1)定义AIDL接口(和Java接口非常类似)

  1. package com.example.testservice;  
  2.   
  3. interface ICat {  
  4.     String getColor();  
  5.     double getWeight();  
  6. }  

(2)定以好上面接口后保存,ADT工具会自动在gen.com.example.service目录下生成一个ICat.jar接口,在该接口中包含一个Stub内部类,该内部类实现了IBinder、ICat两个接口,这个Stub类将会作为远程Service的回调类——它实现了IBuilder接口,因此可作为Service的onBind()方法的返回值。这个Stub类就是一个代理类,同样可以实现IBinder的功能,并且还额外实现了ICat远程访问的功能。


自动生成的ICat.java接口

  1. /* 
  2.  * This file is auto-generated.  DO NOT MODIFY. 
  3.  * Original file: D:\\adt-bundle-windows-x86-20130729\\eclipse\\workspace\\TestService\\src\\com\\example\\testservice\\ICat.aidl 
  4.  */  
  5. package com.example.testservice;  
  6.   
  7. public interface ICat extends android.os.IInterface {  
  8.     /** Local-side IPC implementation stub class. */  
  9.     public static abstract class Stub extends android.os.Binder implements  
  10.             com.example.testservice.ICat {  
  11.         private static final java.lang.String DESCRIPTOR = "com.example.testservice.ICat";  
  12.   
  13.         /** Construct the stub at attach it to the interface. */  
  14.         public Stub() {  
  15.             this.attachInterface(this, DESCRIPTOR);  
  16.         }  
  17.   
  18.         /** 
  19.          * Cast an IBinder object into an com.example.testservice.ICat 
  20.          * interface, generating a proxy if needed. 
  21.          */  
  22.         public static com.example.testservice.ICat asInterface(  
  23.                 android.os.IBinder obj) {  
  24.             if ((obj == null)) {  
  25.                 return null;  
  26.             }  
  27.             android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);  
  28.             if (((iin != null) && (iin instanceof com.example.testservice.ICat))) {  
  29.                 return ((com.example.testservice.ICat) iin);  
  30.             }  
  31.             return new com.example.testservice.ICat.Stub.Proxy(obj);  
  32.         }  
  33.   
  34.         @Override  
  35.         public android.os.IBinder asBinder() {  
  36.             return this;  
  37.         }  
  38.   
  39.         @Override  
  40.         public boolean onTransact(int code, android.os.Parcel data,  
  41.                 android.os.Parcel reply, int flags)  
  42.                 throws android.os.RemoteException {  
  43.             switch (code) {  
  44.             case INTERFACE_TRANSACTION: {  
  45.                 reply.writeString(DESCRIPTOR);  
  46.                 return true;  
  47.             }  
  48.             case TRANSACTION_getColor: {  
  49.                 data.enforceInterface(DESCRIPTOR);  
  50.                 java.lang.String _result = this.getColor();  
  51.                 reply.writeNoException();  
  52.                 reply.writeString(_result);  
  53.                 return true;  
  54.             }  
  55.             case TRANSACTION_getWeight: {  
  56.                 data.enforceInterface(DESCRIPTOR);  
  57.                 double _result = this.getWeight();  
  58.                 reply.writeNoException();  
  59.                 reply.writeDouble(_result);  
  60.                 return true;  
  61.             }  
  62.             }  
  63.             return super.onTransact(code, data, reply, flags);  
  64.         }  
  65.   
  66.         private static class Proxy implements com.example.testservice.ICat {  
  67.             private android.os.IBinder mRemote;  
  68.   
  69.             Proxy(android.os.IBinder remote) {  
  70.                 mRemote = remote;  
  71.             }  
  72.   
  73.             @Override  
  74.             public android.os.IBinder asBinder() {  
  75.                 return mRemote;  
  76.             }  
  77.   
  78.             public java.lang.String getInterfaceDescriptor() {  
  79.                 return DESCRIPTOR;  
  80.             }  
  81.   
  82.             @Override  
  83.             public java.lang.String getColor()  
  84.                     throws android.os.RemoteException {  
  85.                 android.os.Parcel _data = android.os.Parcel.obtain();  
  86.                 android.os.Parcel _reply = android.os.Parcel.obtain();  
  87.                 java.lang.String _result;  
  88.                 try {  
  89.                     _data.writeInterfaceToken(DESCRIPTOR);  
  90.                     mRemote.transact(Stub.TRANSACTION_getColor, _data, _reply,  
  91.                             0);  
  92.                     _reply.readException();  
  93.                     _result = _reply.readString();  
  94.                 } finally {  
  95.                     _reply.recycle();  
  96.                     _data.recycle();  
  97.                 }  
  98.                 return _result;  
  99.             }  
  100.   
  101.             @Override  
  102.             public double getWeight() throws android.os.RemoteException {  
  103.                 android.os.Parcel _data = android.os.Parcel.obtain();  
  104.                 android.os.Parcel _reply = android.os.Parcel.obtain();  
  105.                 double _result;  
  106.                 try {  
  107.                     _data.writeInterfaceToken(DESCRIPTOR);  
  108.                     mRemote.transact(Stub.TRANSACTION_getWeight, _data, _reply,  
  109.                             0);  
  110.                     _reply.readException();  
  111.                     _result = _reply.readDouble();  
  112.                 } finally {  
  113.                     _reply.recycle();  
  114.                     _data.recycle();  
  115.                 }  
  116.                 return _result;  
  117.             }  
  118.         }  
  119.   
  120.         static final int TRANSACTION_getColor = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);  
  121.         static final int TRANSACTION_getWeight = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);  
  122.     }  
  123.   
  124.     public java.lang.String getColor() throws android.os.RemoteException;  
  125.   
  126.     public double getWeight() throws android.os.RemoteException;  
  127. }  
(3)定义一个Service实现类,该Service的onBind()方法所返回的IBinder对象应该是ADT所生成的ICat.Stub的子类的实例。这一步的主要作用是将上面创建的接口暴漏给客户端。

  1. package com.example.testservice;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import com.example.testservice.ICat.Stub;  
  7.   
  8. import android.app.Service;  
  9. import android.content.Intent;  
  10. import android.os.IBinder;  
  11. import android.os.RemoteException;  
  12.   
  13. public class AidlService extends Service{  
  14.       
  15.     private CatBinder catBinder;  
  16.     Timer timer = new Timer();  
  17.     String[] colors = new String[]{  
  18.             "红色",  
  19.             "黄色",  
  20.             "黑色"  
  21.     };  
  22.     double[] weights = new double[]{  
  23.             2.3,  
  24.             3.1,  
  25.             1.58  
  26.     };  
  27.       
  28.     private String color;  
  29.     private double weight;  
  30.   
  31.       
  32.     @Override  
  33.     public IBinder onBind(Intent intent) {    
  34.         /* 
  35.          * 返回catBinder对象 
  36.          * 在绑定本地Service的情况下,该catBinder对象会直接传给客户端的 
  37.          * ServiceConnection对象的onServiceConnected方法的第二个参数; 
  38.          * 在绑定远程Service的情况下,只将catBinder对象的代理传给客户端的 
  39.          * ServiceConnection对象的onServiceConnected方法的第二个参数; 
  40.          */  
  41.         return catBinder;  
  42.     }  
  43.       
  44.     //继承Stub,也就是实现了ICat接口,并实现了IBinder接口  
  45.     public class CatBinder extends Stub{  
  46.   
  47.         @Override  
  48.         public String getColor() throws RemoteException {  
  49.             // TODO Auto-generated method stub  
  50.             return color;  
  51.         }  
  52.   
  53.         @Override  
  54.         public double getWeight() throws RemoteException {  
  55.             // TODO Auto-generated method stub  
  56.             return weight;  
  57.         }  
  58.           
  59.     }  
  60.       
  61.     @Override  
  62.     public void onCreate() {  
  63.         super.onCreate();  
  64.         catBinder = new CatBinder();  
  65.         timer.schedule(new TimerTask() {  
  66.               
  67.             @Override  
  68.             public void run() {  
  69.                 int rand = (int)(Math.random() * 3);  
  70.                 color = colors[rand];  
  71.                 weight = weights[rand];  
  72.                 System.out.println("---------" + rand);  
  73.             }  
  74.         }, 0800);  
  75.     }  
  76.   
  77. }  

(4)在AndroidMainfest.xml文件中配置该Service

  1. <service android:name=".AidlService">  
  2.     <intent-filter>  
  3.         <action android:name="com.example.testservice.action.AIDL_SERVICE"/>  
  4.     </intent-filter>  
  5. </service>  

(5)客户端访问AIDL Service

上面说过AIDL是定义在两个进程之间通信的一个接口,既然是一个通信协议,客户端同样需要前面定义的AIDL接口,所以第一步就是将AIDL文件复制到客户端应用中。

  1. package com.example.testservice;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.Service;  
  5. import android.content.ComponentName;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.IBinder;  
  9. import android.os.RemoteException;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.EditText;  
  14.   
  15. public class AidlClient extends Activity{  
  16.     private ICat catService;  
  17.     private Button get;  
  18.     EditText color, weight;  
  19.     private ServiceConnection conn = new ServiceConnection() {  
  20.           
  21.         @Override  
  22.         public void onServiceDisconnected(ComponentName name) {  
  23.               
  24.         }  
  25.           
  26.         @Override  
  27.         public void onServiceConnected(ComponentName name, IBinder service) {  
  28.             //获取远程Service的onBind方法返回的对象的代理  
  29.             catService = ICat.Stub.asInterface(service);  
  30.         }  
  31.     };  
  32.       
  33.     protected void onCreate(android.os.Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setContentView(R.layout.main);  
  36.         get = (Button)findViewById(R.id.get);  
  37.         color = (EditText)findViewById(R.id.color);  
  38.         weight = (EditText)findViewById(R.id.weight);  
  39.         //创建所需绑定的Service的Intent  
  40.         Intent intent = new Intent();  
  41.         intent.setAction("com.example.testservice.action.AIDL_SERVICE");  
  42.         bindService(intent, conn, Service.BIND_AUTO_CREATE);  
  43.         get.setOnClickListener(new OnClickListener() {  
  44.               
  45.             @Override  
  46.             public void onClick(View arg0) {  
  47.                 try {  
  48.                     color.setText(catService.getColor());  
  49.                     weight.setText(catService.getWeight() + "");  
  50.                 } catch (RemoteException e) {  
  51.                     e.printStackTrace();  
  52.                 }  
  53.             }  
  54.         });  
  55.     };  
  56.       
  57.     @Override  
  58.     protected void onDestroy() {  
  59.         super.onDestroy();  
  60.         //解除绑定  
  61.         this.unbindService(conn);  
  62.     }  
  63. }  


下一篇将介绍如何在进程之间传递复杂数据

0 0
原创粉丝点击