Android開發者指南(6) —— AIDL

前言html

  本章內容爲開發者指南(Dev Guide)/Developing/Tools/aidl,版本爲Android2.3 r1,翻譯來自"移動雲_文斌",歡迎訪問它的博客:"http://blog.csdn.net/caowenbin",再次感謝"移動雲_文斌" !期待你一塊兒參與翻譯Android的相關資料,聯繫我over140@gmail.com。
 java

 

聲明android

  歡迎轉載,但請保留文章原始出處:)
 編程

    農民伯伯:http://over140.blog.51cto.com/安全

    Android中文翻譯組:http://goo.gl/6vJQlapp

 

原文
   http://developer.android.com/guide/developing/tools/aidl.html ( 注意: 3.0 r1 之後移到 Appendix )

 

正文

  使用AIDL設計遠程接口(Designing a Remote Interface Using AIDL)編程語言

因爲每一個應用程序都運行在本身的進程空間,而且能夠從應用程序UI運行另外一個服務進程,並且常常會在不一樣的進程間傳遞對象。在Android平臺,一個進程一般不能訪問另外一個進程的內存空間,因此要想對話,須要將對象分解成操做系統能夠理解的基本單元,而且有序的經過進程邊界。ide

經過代碼來實現這個數據傳輸過程是冗長乏味的,Android提供了AIDL工具來處理這項工做。工具

AIDL (Android Interface Definition Language)是一種IDL 語言,用於生成能夠在Android設備上兩個進程之間進行進程間通訊(IPC)的代碼。若是在一個進程中(例如Activity)要調用另外一個進程中(例如Service)對象的操做,就可使用AIDL生成可序列化的參數。ui

AIDL IPC機制是面向接口的,像COMCorba同樣,可是更加輕量級。它是使用代理類在客戶端和實現端傳遞數據。

 

使用AIDL實現IPC(Implementing IPC Using AIDL)

使用AIDL實現IPC服務的步驟是:

1.         建立.aidl文件-該文件(YourInterface.aidl)定義了客戶端可用的方法和數據的接口。

2.         makefile文件中加入.aidl文件-Eclipse中的ADT插件提供管理功能)Android包括名爲AIDL的編譯器,位於tools/文件夾。

3.         實現接口-AIDL編譯器從AIDL接口文件中利用Java語言建立接口,該接口有一個繼承的命名爲Stub的內部抽象類(而且實現了一些IPC調用的附加方法),要作的就是建立一個繼承於YourInterface.Stub的類而且實如今.aidl文件中聲明的方法。

4.         向客戶端公開接口-若是是編寫服務,應該繼承Service而且重載Service.onBind(Intent) 以返回實現了接口的對象實例

 

  建立.aidl文件(Create an .aidl File)

AIDL使用簡單的語法來聲明接口,描述其方法以及方法的參數和返回值。這些參數和返回值能夠是任何類型,甚至是其餘AIDL生成的接口。重要的是必須導入全部非內置類型,哪怕是這些類型是在與接口相同的包中。下面是AIDL能支持的數據類型:

* Java編程語言的主要類型 (int, boolean) 不須要 import 語句。

* 如下的類 (不須要import 語句):

 String

 List -列表中的全部元素必須是在此列出的類型,包括其餘AIDL生成的接口和可打包類型。List能夠像通常的類(例如List<String>)那樣使用,另外一邊接收的具體類通常是一個ArrayList,這些方法會使用List接口。

 Map - Map中的全部元素必須是在此列出的類型,包括其餘AIDL生成的接口和可打包類型。通常的maps(例如Map<String,Integer>)不被支持,另外一邊接收的具體類通常是一個HashMap,這些方法會使用Map接口。

 CharSequence -該類是被TextView和其餘控件對象使用的字符序列。

* 一般引引用方式傳遞的其餘AIDL生成的接口,必需要import 語句聲明

* 實現了Parcelable protocol 以及按值傳遞的自定義類,必需要import 語句聲明。

如下是基本的AIDL語法:

  

 

  實現接口(Implementing the Interface)

         AIDL生成了與.aidl文件同名的接口,若是使用Eclipse插件,AIDL會作爲編譯過程的一部分自動運行(不須要先運行AIDL再編譯項目),若是沒有插件,就要先運行AIDL

         生成的接口包含一個名爲Stub的抽象的內部類,該類聲明瞭全部.aidl中描述的方法,Stub還定義了少許的輔助方法,尤爲是asInterface(),經過它或以得到IBinder(當applicationContext.bindService()成功調用時傳遞到客戶端的onServiceConnected())而且返回用於調用IPC方法的接口實例,更多細節參見Calling an IPC Method

         要實現本身的接口,就從YourInterface.Stub類繼承,而後實現相關的方法(能夠建立.aidl文件而後實現stub方法而不用在中間編譯,Android編譯過程會在.java文件以前處理.aidl文件)。

         這個例子實現了對 IRemoteService 接口的調用,這裏使用了匿名對象而且只有一個 getPid() 接口。

   

   這裏是實現接口的幾條說明:

 * 不會有返回給調用方的異常

 * 默認IPC調用是同步的。若是已知IPC服務端會花費不少毫秒才能完成,那就不要在ActivityView線程中調用,不然會引發應用程序掛起(Android可能會顯示「應用程序未響應」對話框),能夠試着在獨立的線程中調用。

 * AIDL接口中只支持方法,不能聲明靜態成員。

 

  向客戶端暴露接口(Exposing Your Interface to Clients)

         在完成了接口的實現後須要向客戶端暴露接口了,也就是發佈服務,實現的方法是繼承 Service,而後實現以Service.onBind(Intent)返回一個實現了接口的類對象。下面的代碼片段表示了暴露IRemoteService接口給客戶端的方式。

public   class  RemoteService  extends  Service {
...
@Override
    
public  IBinder onBind(Intent intent) {
        
//  Select the interface to return.  If your service only implements
        
//  a single interface, you can just return it here without checking
        
//  the Intent.
         if  (IRemoteService. class .getName().equals(intent.getAction())) {
            
return  mBinder;
        }
        
if  (ISecondary. class .getName().equals(intent.getAction())) {
            
return  mSecondaryBinder;
        }
        
return   null ;
    }

    
/**
     * The IRemoteInterface is defined through IDL
     
*/
    
private   final  IRemoteService.Stub mBinder  =   new  IRemoteService.Stub() {
        
public   void  registerCallback(IRemoteServiceCallback cb) {
            
if  (cb  !=   null ) mCallbacks.register(cb);
        }
        
public   void  unregisterCallback(IRemoteServiceCallback cb) {
            
if  (cb  !=   null ) mCallbacks.unregister(cb);
        }
    };

    
/**
     * A secondary interface to the service.
     
*/
    
private   final  ISecondary.Stub mSecondaryBinder  =   new  ISecondary.Stub() {
        
public   int  getPid() {
            
return  Process.myPid();
        }
        
public   void  basicTypes( int  anInt,  long  aLong,  boolean  aBoolean,
                
float  aFloat,  double  aDouble, String aString) {
        }
    };

}

  

  使用可打包接口傳遞參數Pass by value Parameters using Parcelables

若是有類想要能過AIDL在進程之間傳遞,這一想法是能夠實現的,必須確保這個類在IPC的兩端的有效性,一般的情形是與一個啓動的服務通訊。

這裏列出了使類可以支持Parcelable4個步驟:【譯者注:原文爲5,但列表爲4項,疑爲做者筆誤】

1.         使該類實現Parcelabel接口。

2.         實現public void writeToParcel(Parcel out) 方法,以即可以將對象的當前狀態寫入包裝對象中。

3.         增長名爲CREATOR的構造器到類中,並實現Parcelable.Creator接口。

4.         最後,但一樣重要的是,建立AIDL文件聲明這個可打包的類(見下文),若是使用的是自定義的編譯過程,那麼不要編譯此AIDL文件,它像C語言的頭文件同樣不須要編譯。

AIDL會使用這些方法的成員序列化和反序列化對象。

這個例子演示瞭如何讓Rect類實現Parcelable接口。

import  android.os.Parcel;
import  android.os.Parcelable;
public   final   class  Rect  implements  Parcelable {
public   int  left;
public   int  top;
public   int  right;
public   int  bottom;

public   static   final  Parcelable.Creator < Rect >  CREATOR  =   new  Parcelable.Creator < Rect > () {
   
public  Rect createFromParcel(Parcel in) {
       
return   new  Rect(in);
   }

    
public  Rect[] newArray( int  size) {
            
return   new  Rect[size];
        }
    };

public  Rect() {
}

private  Rect(Parcel in) {
   readFromParcel(in);
}

public   void  writeToParcel(Parcel out) {
    out.writeInt(left);
    out.writeInt(top);
    out.writeInt(right);
    out.writeInt(bottom);
}

public   void  readFromParcel(Parcel in) {
    left 
=  in.readInt();
    top 
=  in.readInt();
    right 
=  in.readInt();
    bottom 
=  in.readInt();
}
}

   這個是Rect.aidl文件。

 

   序列化Rect類的工做至關簡單,對可打包的其餘類型的數據能夠參見Parcel類。

   警告 :不要忘了對從其餘進程接收到的數據進行安全檢查。在上面的例子中, rect 要從數據包中讀取 4 個數值,須要確認不管調用方想要作什麼,這些數值都是在可接受的範圍以內。想要了解更多的關於保持應用程序安全的內容,可參見 Security and Permissions

 

  調用IPC方法(Calling an IPC Method)

         這裏給出了調用遠端接口的步驟:

1.         聲明.aidl文件中定義的接口類型的變量。

2.         實現ServiceConnection

3.         調用Context.bindService(),傳遞ServiceConnection的實現

4.         ServiceConnection.onServiceConnected()方法中會接收到IBinder對象,調用YourInterfaceName.Stub.asInterface((IBinder)service)將返回值轉換爲YourInterface類型

5.         調用接口中定義的方法。應該老是捕獲鏈接被打斷時拋出的DeadObjectException異常,這是遠端方法惟一的異常。

6.         調用Context.unbindService()斷開鏈接

這裏是幾個調用IPC服務的提示:

* 對象是在進程間進行引用計數

* 能夠發送匿名對象做爲方法參數

         如下是演示調用 AIDL 建立的服務,能夠在 ApiDemos 項目中獲取遠程服務的示例。
public   static   class  Binding  extends  Activity {

/**  The primary interface we will be calling on the service.  */
IRemoteService mService 
=   null ;
/**  Another interface we use on the service.  */
ISecondary mSecondaryService 
=   null ;
Button mKillButton;
TextView mCallbackText;
private   boolean  mIsBound;
/**
* Standard initialization of this activity.  Set up the UI, then wait
* for the user to poke it before doing anything.
*/
@Override
protected   void  onCreate(Bundle savedInstanceState) {
    
super .onCreate(savedInstanceState);
    setContentView(R.layout.remote_service_binding);
    
//  Watch for button clicks.
    Button button  =  (Button)findViewById(R.id.bind);
    button.setOnClickListener(mBindListener);
    button 
=  (Button)findViewById(R.id.unbind);
    button.setOnClickListener(mUnbindListener);
    mKillButton 
=  (Button)findViewById(R.id.kill);
    mKillButton.setOnClickListener(mKillListener);
    mKillButton.setEnabled(
false ); 

    mCallbackText 
=  (TextView)findViewById(R.id.callback);
   mCallbackText.setText(
" Not attached. " );
}

/**
  * Class for interacting with the main interface of the service.
  
*/
private  ServiceConnection mConnection  =   new  ServiceConnection() {
   
public   void  onServiceConnected(ComponentName className, IBinder service) {
        
//  This is called when the connection with the service has been
        
//  established, giving us the service object we can use to
        
//  interact with the service.  We are communicating with our
        
//  service through an IDL interface, so get a client-side
        
//  representation of that from the raw service object.
        mService  =  IRemoteService.Stub.asInterface(service);
        mKillButton.setEnabled(
true );
        mCallbackText.setText(
" Attached. " );
 
        
//  We want to monitor the service for as long as we are
        
//  connected to it.
         try  {
                mService.registerCallback(mCallback);
        } 
catch  (RemoteException e) {
            
//  In this case the service has crashed before we could even
            
//  do anything with it; we can count on soon being
            
//  disconnected (and then reconnected if it can be restarted)
            
//  so there is no need to do anything here.
        }

       
//  As part of the sample, tell the user what happened.
       Toast.makeText(Binding. this , R.string.remote_service_connected,
             Toast.LENGTH_SHORT).show();
    }

    
public   void  onServiceDisconnected(ComponentName className) {
        
//  This is called when the connection with the service has been
        
//  unexpectedly disconnected -- that is, its process crashed.
        mService  =   null ;
        mKillButton.setEnabled(
false );
        mCallbackText.setText(
" Disconnected. " );

        
//  As part of the sample, tell the user what happened.
        Toast.makeText(Binding. this , R.string.remote_service_disconnected,
             Toast.LENGTH_SHORT).show();
    }
};

/**
  * Class for interacting with the secondary interface of the service.
  
*/
private  ServiceConnection mSecondaryConnection  =   new  ServiceConnection() {
   
public   void  onServiceConnected(ComponentName className, IBinder service) {
        
//  Connecting to a secondary interface is the same as any
        
//  other interface.
        mSecondaryService  =  ISecondary.Stub.asInterface(service);
        mKillButton.setEnabled(
true );
    }

    
public   void  onServiceDisconnected(ComponentName className) {
        mSecondaryService 
=   null ;
        mKillButton.setEnabled(
false );
    }
};

private  OnClickListener mBindListener  =   new  OnClickListener() {
   
public   void  onClick(View v) {
        
//  Establish a couple connections with the service, binding
        
//  by interface names.  This allows other applications to be
        
//  installed that replace the remote service by implementing
        
//  the same interface.
       bindService( new  Intent(IRemoteService. class .getName()),
              mConnection, Context.BIND_AUTO_CREATE);
            bindService(
new  Intent(ISecondary. class .getName()),
             mSecondaryConnection, Context.BIND_AUTO_CREATE);
         mIsBound 
=   true ;
         mCallbackText.setText(
" Binding. " );
    }
};

private  OnClickListener mUnbindListener  =   new  OnClickListener() {
    
public   void  onClick(View v) {
       
if  (mIsBound) {
            
//  If we have received the service, and hence registered with
            
//  it, then now is the time to unregister.
             if  (mService  !=   null ) {
                 
try  {
                     mService.unregisterCallback(mCallback);
                 } 
catch  (RemoteException e) {
                    
//  There is nothing special we need to do if the service
                    
//  has crashed.
                }
           }

           
//  Detach our existing connection.
            unbindService(mConnection);
            unbindService(mSecondaryConnection);
            mKillButton.setEnabled(
false );
            mIsBound 
=   false ;
            mCallbackText.setText(
" Unbinding. " );
       }
   }
};

private  OnClickListener mKillListener  =   new  OnClickListener() {
    
public   void  onClick(View v) {
         
//  To kill the process hosting our service, we need to know its
         
//  PID.  Conveniently our service has a call that will return
         
//  to us that information.
          if  (mSecondaryService  !=   null ) {
             
try  {
                
int  pid  =  mSecondaryService.getPid();
                
//  Note that, though this API allows us to request to
                
//  kill any process based on its PID, the kernel will
                
//  still impose standard restrictions on which PIDs you
                
//  are actually able to kill.  Typically this means only
                
//  the process running your application and any additional
                
//  processes created by that app as shown here; packages
                
//  sharing a common UID will also be able to kill each
                
//  other's processes.
                Process.killProcess(pid);
                    mCallbackText.setText(
" Killed service process. " );
          } 
catch  (RemoteException ex) {
                
//  Recover gracefully from the process hosting the
                
//  server dying.
                
//  Just for purposes of the sample, put up a notification.
                Toast.makeText(Binding. this ,
                       R.string.remote_call_failed,
                       Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

//  ----------------------------------------------------------------------
 
//  Code showing how to deal with callbacks.
 
//  ----------------------------------------------------------------------

/**
  * This implementation is used to receive callbacks from the remote
  * service.
*/
private  IRemoteServiceCallback mCallback  =   new  IRemoteServiceCallback.Stub() {
   
/**
     * This is called by the remote service regularly to tell us about
     * new values.  Note that IPC calls are dispatched through a thread
     * pool running in each process, so the code executing here will
     * NOT be running in our main thread like most other things -- so,
     * to update the UI, we need to use a Handler to hop over there.
    
*/
   
public   void  valueChanged( int  value) {
       mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 
0 ));
   }
};
private   static   final   int  BUMP_MSG  =   1 ;
private  Handler mHandler  =   new  Handler() {
   @Override 
public   void  handleMessage(Message msg) {
       
switch  (msg.what) {
           
case  BUMP_MSG:
               mCallbackText.setText(
" Received from service:  "   +  msg.arg1);
               
break ;
           
default :
               
super .handleMessage(msg);         }    } }; }
相關文章
相關標籤/搜索