免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費(fèi)電子書(shū)等14項(xiàng)超值服

開(kāi)通VIP
使用AIDL(Android接口描述語(yǔ)言)設(shè)計(jì)和使用遠(yuǎn)程接口
使用AIDL(Android接口描述語(yǔ)言)設(shè)計(jì)和使用遠(yuǎn)程接口

文章分類(lèi):移動(dòng)開(kāi)發(fā) 關(guān)鍵字: aidl、android 目錄

1 使用AIDL(AndRoid接口描述語(yǔ)言)設(shè)計(jì)和使用遠(yuǎn)程接口
     1.1 使用AIDL實(shí)現(xiàn)IPC
        1.1.1 創(chuàng)建一個(gè)AIDL文件
        1.1.2 實(shí)現(xiàn)接口
        1.1.3 向客戶(hù)端公開(kāi)接口
        1.1.4 使用parcelables進(jìn)行參數(shù)的值傳遞
        1.2 調(diào)用一個(gè)IPC方法

使用AIDL(AndRoid接口描述語(yǔ)言)設(shè)計(jì)和使用遠(yuǎn)程接口

Since each application runs in its own process, and you can write a service that runs in a different process from your Application's UI, sometimes you need to pass objects between processes. On the Android platform, one process can not normally access the memory of another process. So to talk, they need to decompose their objects into primitives that the operating system can understand, and "marshall" the object across that boundary for you.

通常每個(gè)應(yīng)用程序都在它自己的進(jìn)程內(nèi)運(yùn)行,但有時(shí)需要在進(jìn)程間傳遞對(duì)象,你可以通過(guò)應(yīng)用程序UI的方式寫(xiě)個(gè)運(yùn)行在一個(gè)不同的進(jìn)程中的 service。在AndRoid平臺(tái)中,一個(gè)進(jìn)程通常不能訪問(wèn)其他進(jìn)程中的內(nèi)存區(qū)域。所以,他們需要把對(duì)象拆分成操作系統(tǒng)能理解的簡(jiǎn)單形式,以便偽裝成對(duì)象跨越邊界訪問(wèn)。

The code to do that marshalling is tedious to write, so we provide the AIDL tool to do it for you.

編寫(xiě)這種偽裝代碼相當(dāng)?shù)目菰锓ξ?,好在我們提供了AIDL工具可以來(lái)做這件事。

AIDL (Android Interface Definition Language) is an IDL language used to generate code that enables two processes on an Android device to talk using interprocess communication (IPC). If you have code in one process (for example, in an Activity) that needs to call methods on an object in another process (for example, a Service), you would use AIDL to generate code to marshall the parameters.

AIDL(AndRoid接口描述語(yǔ)言)是一個(gè)IDL語(yǔ)言,它可以生成一段代碼,可以使在一個(gè)AndRoid設(shè)備上運(yùn)行的兩個(gè)進(jìn)程使用內(nèi)部通信進(jìn)程進(jìn)行交互。如果你需要在一個(gè)進(jìn)程中(例如:在一個(gè)Activity中)訪問(wèn)另一個(gè)進(jìn)程中(例如:一個(gè)Service)某個(gè)對(duì)象的方法,你就可以使用 AIDL來(lái)生成這樣的代碼來(lái)偽裝傳遞各種參數(shù)。

The AIDL IPC mechanism is interface-based, similar to COM or Corba, but lighter weight. It uses a proxy class to pass values between the client and the implementation.

AIDL IPC的機(jī)制是基于接口的,和COM或Corba類(lèi)似,但它是輕量級(jí)的。它使用代理類(lèi)在客戶(hù)端和實(shí)現(xiàn)層間傳遞值。

This page includes the following main topics:

本頁(yè)包含以下主題:

Implementing IPC Using AIDL

Calling an .aidl (IPC) Class

使用AIDL實(shí)現(xiàn)IPC

調(diào)用一個(gè)AIDL(IPC)類(lèi)


使用AIDL實(shí)現(xiàn)IPC

Follow these steps to implement an IPC service using AIDL.

使用AIDL實(shí)現(xiàn)一個(gè)IPC有下列步驟:

1.Create your .aidl file - This file defines an interface (YourInterface.aidl) that defines the methods and fields available to a client.

1、創(chuàng)建你的AIDL文件 - 這個(gè)文件定義一個(gè)接口(YourInterface.aidl),該接口定義了可供客戶(hù)端訪問(wèn)的方法和屬性。

2.Add the .aidl file to your makefile - (the Eclipse plugin manages this for you). Android includes the compiler, called AIDL, in the tools/ directory.

2、添加AIDL文件到你的makefile中-(Eclipse plugin可以幫你管理)。AndRoid包括編譯器,AIDL調(diào)用,這些都能在tools/directory中找到。

3.Implement your interface methods - The AIDL compiler creates an interface in the Java programming language from your AIDL interface. This interface has an inner abstract class named Stub that inherits the interface (and implements a few additional methods necessary for the IPC call). You must create a class that extends YourInterface.Stub and implements the methods you declared in your .aidl file.

3、實(shí)現(xiàn)接口方法-AIDL編譯器從你的AIDL接口中使用JAVA編程語(yǔ)言來(lái)創(chuàng)建一個(gè)接口。這個(gè)接口有一個(gè)名為Stub的內(nèi)部抽象類(lèi),它繼承接口(并實(shí)現(xiàn)供IPC調(diào)用的所必需的幾個(gè)附加方法)。你必須創(chuàng)建一個(gè)類(lèi)來(lái)實(shí)現(xiàn)該接口。

4.Expose your interface to clients - If you're writing a service, you should extend Service and override getBinder() to returning an instance of your class that implements your interface.

4、向客戶(hù)端開(kāi)放接口-如果你寫(xiě)個(gè)service,你應(yīng)該擴(kuò)展該Service并重載getBinder()方法來(lái)返回一個(gè)實(shí)現(xiàn)上述接口的類(lèi)的實(shí)例。
[編輯] 創(chuàng)建一個(gè)AIDL文件

AIDL is a simple syntax that lets you declare an interface with one or more methods, that can take parameters and return values. These parameters and return values can be of any type, even other AIDL-generated interfaces. However, it is important to note that you must import all non-built-in types, even if they are defined in the same package as your interface. Here are the data types that AIDL can support:

AIDL語(yǔ)法簡(jiǎn)單,你可以用來(lái)聲明一個(gè)帶一個(gè)或多個(gè)方法的接口,也可以傳遞參數(shù)和返回值。這些參數(shù)和返回值可以是任何類(lèi)型,甚至是其他的AIDL 生成的接口。然而,值得重視的是你必須導(dǎo)入所有的non-bult-in類(lèi)型,即使他們已經(jīng)作為接口在其他包里定義了。下面是些AIDL支持的數(shù)據(jù)類(lèi)型:

Primitive Java programming language types (int, boolean, etc) — No import statement is needed.

簡(jiǎn)單Java編程語(yǔ)言類(lèi)型(int,boolean等) -不需要import聲明。

One of the following classes (no import statements needed):

下面類(lèi)之一(不需要import聲明)

Java 代碼

   1. .String  
   2.  .List - All elements in the List must be one of the types in this list, including other AIDL-generated interfaces  
   3.   and parcelables. List may optionally be used as a "generic" class (e.g. List<String>). The actual concrete class  
   4.   that the other side will receive will always be an ArrayList, although the method will be generated to use the  
   5.   List interface.  
   6.  .List - List 中的所有元素都必須是可支持的類(lèi)型中的一個(gè),包括其他AIDL生成接口和parcelables。List可以作為泛型類(lèi)來(lái)靈活使用(比如  
   7.    List<String>)。 而實(shí)際的接受方的類(lèi)則總是ArrayList,盡管該方法將被生成來(lái)使用List接口。 
   8.  .Map - All elements in the Map must be of one of the types in this list, including other AIDL-generated interfaces 
   9.   and parcelables. Generic maps, (e.g. of the form Map<String,Integer> are not supported. The actual concrete class  
  10.   that the other side will receive will always be a HashMap,although the method will be generated to use the Map interface.  
  11.  .Map - Map 中的所有元素都必須是可支持的類(lèi)型中的一個(gè),包括其他AIDL生成接口和parcelables。泛型化的Maps(比如:Map<Stirng,Integer>)不被支持。 
  12.   而實(shí)際的接受方的類(lèi)則總是 HashMap,盡管該方法將被生成去使用Map接口。 
  13.  .CharSequence - This is useful for the CharSequence types used by TextView and other widget objects.  
  14.  .CharSequence - CharSequence 的作用是可以被TextView和其他Widget對(duì)象使用。 

.String
 .List - All elements in the List must be one of the types in this list, including other AIDL-generated interfaces
  and parcelables. List may optionally be used as a "generic" class (e.g. List<String>). The actual concrete class
  that the other side will receive will always be an ArrayList, although the method will be generated to use the
  List interface.
 .List - List中的所有元素都必須是可支持的類(lèi)型中的一個(gè),包括其他AIDL生成接口和parcelables。List可以作為泛型類(lèi)來(lái)靈活使用(比如
   List<String>)。而實(shí)際的接受方的類(lèi)則總是ArrayList,盡管該方法將被生成來(lái)使用List接口。
 .Map - All elements in the Map must be of one of the types in this list, including other AIDL-generated interfaces
  and parcelables. Generic maps, (e.g. of the form Map<String,Integer> are not supported. The actual concrete class
  that the other side will receive will always be a HashMap,although the method will be generated to use the Map interface.
 .Map - Map中的所有元素都必須是可支持的類(lèi)型中的一個(gè),包括其他AIDL生成接口和parcelables。泛型化的Maps(比如:Map<Stirng,Integer>)不被支持。
  而實(shí)際的接受方的類(lèi)則總是HashMap,盡管該方法將被生成去使用Map接口。
 .CharSequence - This is useful for the CharSequence types used by TextView and other widget objects.
 .CharSequence - CharSequence的作用是可以被TextView和其他Widget對(duì)象使用。



Other AIDL-generated interfaces, which are always passed by reference. An import statement is always needed for these. Custom classes that implement the Parcelable protocol and are passed by value. An import statement is always needed for these.

其他的AIDL生成接口通過(guò)引用方式進(jìn)行傳遞。所以import聲明是必須的。封裝協(xié)議實(shí)現(xiàn)的自定義的類(lèi)是值傳遞的方式。所以import聲明也是必須的。

Here is the basic AIDL syntax:

下面是基本的AIDL語(yǔ)法:

Java 代碼

   1. // My AIDL file, named SomeClass.aidl 
   2. // Note that standard comment syntax is respected. 
   3. // Comments before the import or package statements are not bubbled up 
   4. // to the generated interface, but comments above interface/method/field 
   5. // declarations are added to the generated interface. 
   6. // Include your fully-qualified package statement. 
   7. package com.google.android.sample; 
   8. // See the list above for which classes need 
   9. // import statements (hint--most of them) 
  10. import com.google.android.sample.IAtmService; 
  11. // Declare the interface. 
  12. interface IBankAccountService { 
  13.   // Methods can take 0 or more parameters, and 
  14.   // return a value or void. 
  15.   int getAccountBalance(); 
  16.   void setOwnerNames(in List<String> names); 
  17.   // Methods can even take other AIDL-defined parameters. 
  18.   BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService); 
  19.   // All non-Java primitive parameters (e.g., int, bool, etc) require 
  20.   // a directional tag indicating which way the data will go. Available 
  21.   // values are in, out, inout. (Primitives are in by default, and cannot be otherwise). 
  22.   // Limit the direction to what is truly needed, because marshalling parameters 
  23.   // is expensive. 
  24.   int getCustomerList(in String branch, out String[] customerList); 
  25. } 

 // My AIDL file, named SomeClass.aidl
 // Note that standard comment syntax is respected.
 // Comments before the import or package statements are not bubbled up
 // to the generated interface, but comments above interface/method/field
 // declarations are added to the generated interface.
 // Include your fully-qualified package statement.
 package com.google.android.sample;
 // See the list above for which classes need
 // import statements (hint--most of them)
 import com.google.android.sample.IAtmService;
 // Declare the interface.
 interface IBankAccountService {
   // Methods can take 0 or more parameters, and
   // return a value or void.
   int getAccountBalance();
   void setOwnerNames(in List<String> names);
   // Methods can even take other AIDL-defined parameters.
   BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService);
   // All non-Java primitive parameters (e.g., int, bool, etc) require
   // a directional tag indicating which way the data will go. Available
   // values are in, out, inout. (Primitives are in by default, and cannot be otherwise).
   // Limit the direction to what is truly needed, because marshalling parameters
   // is expensive.
   int getCustomerList(in String branch, out String[] customerList);
 }



實(shí)現(xiàn)接口

AIDL generates an interface file for you with the same name as your .aidl file. If you are using the Eclipse plugin, AIDL will automatically be run as part of the build process (you don't need to run AIDL first and then build your project). If you are not using the plugin, you should run AIDL first.

AIDL生成一個(gè)接口文件,文件名和你的AIDL文件名一致。如果你使用的是Eclipse插件,AIDL會(huì)作為build過(guò)程的一部分自動(dòng)運(yùn)行 (你不需要首先運(yùn)行ADIL然后再去創(chuàng)建你的項(xiàng)目)。否則的話,你需要首先運(yùn)行AIDL。

The generated interface includes an abstract inner class named Stub that declares all the methods that you declared in your .aidl file. Stub also defines a few helper methods, most notably asInterface(), which takes an IBinder (passed to a client's onServiceConnected() implementation when applicationContext.bindService() succeeds), and returns an instance of the interface used to call the IPC methods. See the section Calling an IPC Method for more details on how to make this cast.

生成的接口包括一個(gè)名為Stub的內(nèi)部抽象類(lèi),該類(lèi)聲明了你在aidl文件中聲明的所有方法。Stub也定義幾個(gè)有用的方法,最特別的是 asInterface(),它執(zhí)行一個(gè)IBinder(在 applicationContext.bindService()執(zhí)行成功后傳給客戶(hù)端onServiceConnected()方法),并返回一個(gè)用來(lái)調(diào)用IPC方法的接口實(shí)例。更多細(xì)節(jié)請(qǐng)查看章節(jié)調(diào)用IPC方法。

To implement your interface, extend YourInterface.Stub, and implement the methods. (You can create the .aidl file and implement the stub methods without building between--the Android build process will process .aidl files before .java files.)

實(shí)現(xiàn)接口,擴(kuò)展YourInterface.Stub,并實(shí)現(xiàn)方法成員。(你可以創(chuàng)建一個(gè)aidl文件并實(shí)現(xiàn)stub方法而不用綁定 -AndRoid創(chuàng)建過(guò)程在java文件之前會(huì)處理aidl文件)。

Here is an example of implementing an interface called IRemoteService, which exposes a single method, getPid(), using an anonymous instance:

這里有個(gè)例子,它實(shí)現(xiàn)了一個(gè)調(diào)用IRemoteService的接口,并使用匿名實(shí)例公開(kāi)一個(gè)簡(jiǎn)單的方法gerPid():

Java 代碼

   1. // No need to import IRemoteService if it's in the same project. 
   2. private final IRemoteService.Stub mBinder = new IRemoteService.Stub(){ 
   3.    public int getPid(){ 
   4.        return Process.myPid(); 
   5.    } 
   6. } 

// No need to import IRemoteService if it's in the same project.
private final IRemoteService.Stub mBinder = new IRemoteService.Stub(){
   public int getPid(){
       return Process.myPid();
   }
}



A few rules about implementing your interface:

實(shí)現(xiàn)接口時(shí)有幾個(gè)原則:
Java 代碼

   1. .No exceptions that you throw will be sent back to the caller.  
   2. . 拋出的異常不要返回給調(diào)用者。 
   3. .IPC calls are synchronous. If you know that an IPC service takes more than a few milliseconds to complete,  
   4.  you should not call it in the Activity/View thread, because it might hang the application (Android might display  
   5.  an "Application is Not Responding" dialog). Try to call them in a separate thread.  
   6. .IPC 調(diào)用是同步的。如果你知道一個(gè)IPC服務(wù)需要超過(guò)幾毫秒的時(shí)間才能完成地話,你應(yīng)該避免在Activity/View線程中調(diào)用。 
   7.   因 為它會(huì)掛起應(yīng)用程序(AndRoid可能會(huì)顯示"應(yīng)用程序沒(méi)有響應(yīng)"對(duì)話框)。試著在一個(gè)獨(dú)立的線程中調(diào)用。 
   8. .Only methods are supported; you cannot declare static fields in an AIDL interface.  
   9. . 只有方法才獲得支持;你不能在AIDL接口中聲明靜態(tài)屬性。 

.No exceptions that you throw will be sent back to the caller.
.拋出的異常不要返回給調(diào)用者。
.IPC calls are synchronous. If you know that an IPC service takes more than a few milliseconds to complete,
 you should not call it in the Activity/View thread, because it might hang the application (Android might display
 an "Application is Not Responding" dialog). Try to call them in a separate thread.
.IPC調(diào)用是同步的。如果你知道一個(gè)IPC服務(wù)需要超過(guò)幾毫秒的時(shí)間才能完成地話,你應(yīng)該避免在Activity/View線程中調(diào)用。
  因?yàn)樗鼤?huì)掛起應(yīng)用程序(AndRoid可能會(huì)顯示"應(yīng)用程序沒(méi)有響應(yīng)"對(duì)話框)。試著在一個(gè)獨(dú)立的線程中調(diào)用。
.Only methods are supported; you cannot declare static fields in an AIDL interface.
.只有方法才獲得支持;你不能在AIDL接口中聲明靜態(tài)屬性。



向客戶(hù)端公開(kāi)接口

Now that you've got your interface implementation, you need to expose it to clients. This is known as "publishing your service." To publish a service, inherit Service and implement getBinder() to return an instance of the class that implements your interface. Here's a code snippet of a service that exposes the IRemoteService interface to clients

現(xiàn)在你已完成了接口的實(shí)現(xiàn),你需要向客戶(hù)端公開(kāi)該實(shí)現(xiàn)。這就是我們所熟悉的"發(fā)布服務(wù)"。發(fā)布一個(gè)Service,然后繼承 Service并實(shí)現(xiàn)getBinder()返回一個(gè)實(shí)現(xiàn)的類(lèi)的實(shí)例。下面是個(gè)Service的代碼片斷,該Service向客戶(hù)端公了 IRemoteService接口。

Java 代碼

   1. public class RemoteService extends Service { 
   2. ... 
   3.    @Override 
   4.    public IBinder getBinder() { 
   5.        return mBinder; 
   6.    } 
   7.    /**
   8.     * The IRemoteInterface is defined through IDL
   9.     */ 
  10.    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { 
  11.        public int getPid() { 
  12.            return Process.myPid(); 
  13.        } 
  14.    }; 
  15.  } 

public class RemoteService extends Service {
...
   @Override
   public IBinder getBinder() {
       return mBinder;
   }
   /**
    * The IRemoteInterface is defined through IDL
    */
   private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
       public int getPid() {
           return Process.myPid();
       }
   };
 }



使用parcelables進(jìn)行參數(shù)的值傳遞
Java 代碼

   1. Warning: Parcelables currently do not work if you're using the Eclipse plugin. You will see these errors if you try: 警 告:如果你現(xiàn)在使用Eclipse插件,Parcelables并不能工作。你會(huì)看到以下的錯(cuò)誤信息: 
   2.  
   3.   .aidl files that only declare parcelables don't need to go in the makefile 
   4.   . 僅聲明parcelables的.aidl文件不需要寫(xiě)進(jìn)makefile 
   5.   .aidl can only generate code for interfaces, not parcelables 
   6.   .aidl 只能生成接口代碼,而不是parcelables。 
   7.  
   8. This is a known limitation. Parcelables can still be used with the ant build.xml files or your own custom build system. A workaround is for you to run the aidl tool by hand for all of your interfaces and add them to your Eclipse project. See step 5 below for why Eclipse shouldn't be trying to compile these aidl files. 
   9.  
  10. 這是個(gè)眾所周知的局限。Parcelables仍然可以被ant build的xml文件或自定義的build系統(tǒng)所使用。你應(yīng)該在Eclipse項(xiàng)目中添加一個(gè)工作區(qū),該工作區(qū)可以為所有的接口手動(dòng)運(yùn)行aidl工具。下面的步驟5說(shuō)明為何Eclipse不該嘗試編譯這些aidl文件。 

Warning: Parcelables currently do not work if you're using the Eclipse plugin. You will see these errors if you try: 警告:如果你現(xiàn)在使用Eclipse插件,Parcelables并不能工作。你會(huì)看到以下的錯(cuò)誤信息:

  .aidl files that only declare parcelables don't need to go in the makefile
  .僅聲明parcelables的.aidl文件不需要寫(xiě)進(jìn)makefile
  .aidl can only generate code for interfaces, not parcelables
  .aidl只能生成接口代碼,而不是parcelables。

This is a known limitation. Parcelables can still be used with the ant build.xml files or your own custom build system. A workaround is for you to run the aidl tool by hand for all of your interfaces and add them to your Eclipse project. See step 5 below for why Eclipse shouldn't be trying to compile these aidl files.

這是個(gè)眾所周知的局限。Parcelables仍然可以被ant build的xml文件或自定義的build系統(tǒng)所使用。你應(yīng)該在Eclipse項(xiàng)目中添加一個(gè)工作區(qū),該工作區(qū)可以為所有的接口手動(dòng)運(yùn)行aidl工具。下面的步驟5說(shuō)明為何Eclipse不該嘗試編譯這些aidl文件。



If you have a class that you would like to send from one process to another through an AIDL interface, you can do that. You must ensure that the code for your class is available to the other side of the IPC. Generally, that means that you're talking to a service that you started.

如果你有類(lèi)需要通過(guò)AIDL接口從一個(gè)進(jìn)程發(fā)送到另一個(gè),你必須確保類(lèi)代碼可以被IPC接收端所使用。通常這意味著一開(kāi)始你就要和service 進(jìn)行通訊。

There are five parts to making a class support the Parcelable protocol:

讓類(lèi)支持parcelable協(xié)議,有五點(diǎn)需要注意

   1.Make your class implement the Parcelable interface.  
   1. 讓類(lèi)實(shí)現(xiàn)Parcelable接口。 
   2.Implement the method public void writeToParcel(Parcel out) that takes the current state of the object and writes it to a parcel.  
   2. 實(shí)現(xiàn)public void writeToParcel(Parcel out),該方法可以將當(dāng)前對(duì)象的狀態(tài)寫(xiě)入parcel. 
   3.Implement the method public void readFromParcel(Parcel in) that reads the value in a parcel into your object.  
   3. 實(shí)現(xiàn)public void readFromParcel(Parcel in),該方法可以在 parcel中讀出值到對(duì)象中. 
   4.Add a static field called CREATOR to your class which is an object implementing the Parcelable.Creator interface.  
   4. 向類(lèi)中添加一個(gè)靜態(tài)成員,名為CREATOR。該對(duì)象實(shí)現(xiàn)了 Parcelable.Creator接口. 
   5.Last but not least, add an aidl file for your parcelable class so the AIDL tool can find it, but don't add it to your build. This file is used like a header file in C. You don't compile the aidl file for a parcelable just like you wouldn't normally compile a .h file.  
   5. 向parcelable類(lèi)中添加一個(gè).aidl文件,以便AIDl工具可以找到。但不要向build中添加該文件。該文件的用法類(lèi)似于C中的頭文件.你不需要為parcelable編譯aidl文件,就像你不會(huì)編譯個(gè).h文件一樣。 

AIDL will use these methods and fields in the code it generates to marshall and unmarshall your objects.

AIDL將使用代碼中生成的這些方法和成員來(lái)偽裝或解讀對(duì)象。

Here is an example of how the Rect class implements the Parcelable protocol.

下面的例子說(shuō)明了Rect類(lèi)如何實(shí)現(xiàn)了Parcelable協(xié)議.

Java 代碼

   1. import android.os.Parcel; 
   2.  import android.os.Parcelable; 
   3.  public final class Rect implements Parcelable { 
   4.    public int left; 
   5.    public int top; 
   6.    public int right; 
   7.    public int bottom; 
   8.    public static final Parcelable.Creator<Rect> CREATOR = new Parcelable.Creator<Rect> { 
   9.        public Rect createFromParcel(Parcel in) { 
  10.            return new Rect(in); 
  11.        } 
  12.        public Rect[] newArray(int size) { 
  13.            return new Rect[size]; 
  14.        } 
  15.    }; 
  16.    public Rect() {    } 
  17.    private Rect(Parcel in) { 
  18.        readFromParcel(in); 
  19.    } 
  20.    public void writeToParcel(Parcel out) { 
  21.        out.writeInt(left); 
  22.        out.writeInt(top); 
  23.        out.writeInt(right); 
  24.        out.writeInt(bottom); 
  25.    } 
  26.    public void readFromParcel(Parcel in) { 
  27.        left = in.readInt(); 
  28.        top = in.readInt(); 
  29.        right = in.readInt(); 
  30.        bottom = in.readInt(); 
  31.    } 
  32.  } 

 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();
   }
 }



Here is Rect.aidl for this example

示例的Rect.aidl


   1. package android.graphics; 
   2. // Declare Rect so AIDL can find it and knows that it implements 
   3. // the parcelable protocol. 
   4. parcelable Rect; 

package android.graphics;
// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;



The marshalling in the Rect class is pretty simple. Take a look at the other methods on Parcel to see the other kinds of values you can write to a Parcel.

Rect類(lèi)中的偽裝是相當(dāng)簡(jiǎn)單的。仔細(xì)看看Parcel中的其他方法,你會(huì)看到其他各種值你都可以寫(xiě)進(jìn)Parcel.
Java 代碼

   1. Warning: Don't forget the security implications of receiving data from other processes. In this case, the rect will read four numbers from the parcel, but it is up to you to ensure that these are within the acceptable range of values for whatever the caller is trying to do. See Security and Permissions in Android for more on how to keep your application secure from malware. 
   2.  
   3. 警告:不要忽視從其他進(jìn)程接收數(shù)據(jù)時(shí)的安全性考慮。在本例中,rect將從parcel中讀四個(gè)數(shù)字,而你的工作則是確保這些都在可接受的值得范圍內(nèi)而不管調(diào)用者想要干什么。AndRoid中的安全和訪問(wèn)許可中有更多關(guān)于如何確保應(yīng)用程序安全的信息。 

Warning: Don't forget the security implications of receiving data from other processes. In this case, the rect will read four numbers from the parcel, but it is up to you to ensure that these are within the acceptable range of values for whatever the caller is trying to do. See Security and Permissions in Android for more on how to keep your application secure from malware.

警告:不要忽視從其他進(jìn)程接收數(shù)據(jù)時(shí)的安全性考慮。在本例中,rect將從parcel中讀四個(gè)數(shù)字,而你的工作則是確保這些都在可接受的值得范圍內(nèi)而不管調(diào)用者想要干什么。AndRoid中的安全和訪問(wèn)許可中有更多關(guān)于如何確保應(yīng)用程序安全的信息。


調(diào)用一個(gè)IPC方法

Here are the steps a calling class should make to call your remote interface:

調(diào)用類(lèi)調(diào)用遠(yuǎn)程接口的步驟:
1.Declare a variable of the interface type that your .aidl file defined.
Java 代碼

   1.聲明一個(gè)接口類(lèi)型的變量,該接口類(lèi)型在.aidl文件中定義。 
   2.Implement ServiceConnection.  
   2.實(shí)現(xiàn)ServiceConnection。 
   3.Call ApplicationContext.bindService(), passing in your ServiceConnection implementation.  
   3.調(diào)用ApplicationContext.bindService(),并在 ServiceConnection實(shí)現(xiàn)中進(jìn)行傳遞.  
   4.In your implementation of ServiceConnection.onServiceConnected(), you will receive an IBinder instance (called service).  
   Call YourInterfaceName.Stub.asInterface((IBinder)service) to cast the returned parameter to YourInterface type.  
   4.在ServiceConnection.onServiceConnected()實(shí)現(xiàn)中,你會(huì)接收一個(gè)IBinder實(shí)例(被調(diào)用的Service). 調(diào)用 
   YourInterfaceName.Stub.asInterface((IBinder)service) 將參數(shù)轉(zhuǎn)換為YourInterface類(lèi)型。 
   5.Call the methods that you defined on your interface. You should always trap DeadObjectException exceptions, which are  
   thrown when the connection has broken; this will be the only exception thrown by remote methods.  
   5.調(diào)用接口中定義的方法。 你總會(huì)捕捉到DeadObjectException異常,該異常在連接斷開(kāi)時(shí)被拋出。它只會(huì)被遠(yuǎn)程方法拋出。 
   6.To disconnect, call ApplicationContext.unbindService() with the instance of your interface.  
   6. 斷開(kāi)連接,調(diào)用接口實(shí)例中的 ApplicationContext.unbindService() 

A few comments on calling an IPC service:
調(diào)用IPC服務(wù)需要注意幾點(diǎn):
Java 代碼

   1. .Objects are reference counted across processes.  
   2.  
   3. .You can send anonymous objects as method arguments.  
   4. . 匿名對(duì)象可以通過(guò)方法參數(shù)發(fā)送。 

.Objects are reference counted across processes.

.You can send anonymous objects as method arguments.
.匿名對(duì)象可以通過(guò)方法參數(shù)發(fā)送。

Here is some sample code demonstrating calling an AIDL-created service, taken from the Remote Activity sample in the ApiDemos project.

下面的代碼展示了在ApiDemos項(xiàng)目從遠(yuǎn)程Activity例子中調(diào)用AIDL創(chuàng)建Service的過(guò)程。

Java 代碼

   1. public class RemoteServiceBinding extends Activity{ 
   2.     IRemoteService mService = null; 
   3.     Button mKillButton; 
   4.     private boolean mIsBound; 
   5.     @Override 
   6.     protected void onCreate(Bundle icicle)    { 
   7.         super.onCreate(icicle); 
   8.         setContentView(R.layout.remote_service_binding); 
   9.         // Watch for button clicks. 
  10.         Button button = (Button)findViewById(R.id.bind); 
  11.         button.setOnClickListener(mBindListener); 
  12.         button = (Button)findViewById(R.id.unbind); 
  13.         button.setOnClickListener(mUnbindListener); 
  14.         mKillButton = (Button)findViewById(R.id.kill); 
  15.         mKillButton.setOnClickListener(mKillListener);  
  16.         mKillButton.setEnabled(false); 
  17.     } 
  18.     private ServiceConnection mConnection = new ServiceConnection()    { 
  19.         public void onServiceConnected(ComponentName className, IBinder service)        { 
  20.             // This is called when the connection with the service has been 
  21.             // established, giving us the service object we can use to 
  22.             // interact with the service.  We are communicating with our 
  23.             // service through an IDL interface, so get a client-side 
  24.             // representation of that from the raw service object. 
  25.             mService = IRemoteService.Stub.asInterface((IBinder)service); 
  26.             mKillButton.setEnabled(true); 
  27.             // As part of the sample, tell the user what happened. 
  28.             NotificationManager nm = (NotificationManager) 
  29.                 getSystemService(NOTIFICATION_SERVICE); 
  30.             nm.notifyWithText(R.string.remote_service_connected, 
  31.                       getText(R.string.remote_service_connected), 
  32.                       NotificationManager.LENGTH_SHORT, 
  33.                       null); 
  34.         } 
  35.         public void onServiceDisconnected(ComponentName className)        { 
  36.             // This is called when the connection with the service has been 
  37.             // unexpectedly disconnected -- that is, its process crashed. 
  38.             mService = null; 
  39.             mKillButton.setEnabled(false); 
  40.             // As part of the sample, tell the user what happened. 
  41.             NotificationManager nm = (NotificationManager) 
  42.                     getSystemService(NOTIFICATION_SERVICE); 
  43.             nm.notifyWithText(R.string.remote_service_disconnected, 
  44.                       getText(R.string.remote_service_disconnected), 
  45.                       NotificationManager.LENGTH_SHORT, 
  46.                       null); 
  47.         } 
  48.     }; 
  49.     private OnClickListener mBindListener = new OnClickListener()    { 
  50.         public void onClick(View v)        { 
  51.             // Establish a connection with the service, by its class name. 
  52.             bindService(new Intent(RemoteServiceBinding.this, 
  53.                         RemoteService.class), 
  54.                     null, mConnection, Context.BIND_AUTO_CREATE); 
  55.             mIsBound = true; 
  56.         } 
  57.     }; 
  58.     private OnClickListener mUnbindListener = new OnClickListener()    { 
  59.         public void onClick(View v)        { 
  60.             if (mIsBound) { 
  61.                 // Detach our existing connection. 
  62.                 unbindService(mConnection); 
  63.                 mKillButton.setEnabled(false); 
  64.                 mIsBound = false; 
  65.             } 
  66.         } 
  67.     }; 
  68.     private OnClickListener mKillListener = new OnClickListener()    { 
  69.         public void onClick(View v)        { 
  70.             // To kill the process hosting our service, we need to know its 
  71.             // PID.  Conveniently our service has a call that will return 
  72.             // to us that information. 
  73.             if (mService != null) { 
  74.                 int pid = -1; 
  75.                 try { 
  76.                     pid = mService.getPid(); 
  77.                 } catch (DeadObjectException ex) { 
  78.                     // Recover gracefully from the process hosting the 
  79.                     // server dying. 
  80.                     // Just for purposes of the sample, put up a notification. 
  81.                     NotificationManager nm = (NotificationManager) 
  82.                         getSystemService(NOTIFICATION_SERVICE); 
  83.                     nm.notifyWithText(R.string.remote_call_failed, 
  84.                               getText(R.string.remote_call_failed), 
  85.                               NotificationManager.LENGTH_SHORT, 
  86.                               null); 
  87.                 } 
  88.                 if (pid > 0) { 
  89.                     // Go away! 
  90.                     Process.killProcess(pid); 
  91.                 } 
  92.             } 
  93.         } 
  94.     }; 
  95. }

本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶(hù)發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
Android使用AIDL設(shè)計(jì)和調(diào)用遠(yuǎn)程接口
android service中stub作用是什么?
Android AIDL使用詳解
Binder基本概念流程學(xué)習(xí)
AOSP/安卓的架構(gòu)演進(jìn)之二三事
Binder:為什么要通過(guò)onTransact()調(diào)用目標(biāo)方法
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服