首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

Android Interface Definition Language (AIDL) android接口定义语言 开发文档翻译 - 二

2013-08-01 
Android Interface Definition Language (AIDL) android接口定义语言 开发文档翻译 - 2由于本人英文能力实

Android Interface Definition Language (AIDL) android接口定义语言 开发文档翻译 - 2

由于本人英文能力实在有限,不足之初敬请谅解

本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接链接

?

Passing Objects over IPC

跨进程传递对象

If you have a class that you would like to send from one process to another through an IPC interface, you can do that.?

However, you must ensure that the code for your class is available to the other side of the IPC channel and your class must support the Parcelable interface.?

Supporting the Parcelable interface is important because it allows the Android system to decompose objects into primitives that can be marshalled across processes.

如果你想通过IPC接口把一个类从一个进程传递到另一个进程中,那么是可以的。

然而,你必须保证为你的类而写的代码也是对IPC通道另一端是可用的,并且你的类必须支持Parcelable接口

支持Parcelable接口是很重要的,因为它允许Android系统把对象分解为可以被组织跨进程传输基本单元

?

To create a class that supports the Parcelable protocol, you must do the following:

为了建立一个支持Parcelable协议的类,你必须遵守下面的规则:

?

Make your class implement the Parcelable interface.

Implement writeToParcel, which takes the current state of the object and writes it to a Parcel.

Add a static field called CREATOR to your class which is an object implementing the Parcelable.Creator interface.

Finally, create an .aidl file that declares your parcelable class (as shown for the Rect.aidl file, below).

If you are using a custom build process, do not add the .aidl file to your build. Similar to a header file in the C language, this .aidl file isn't compiled.

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

要实现Parcelable接口

实现writeToParcel,它是用来把对象的当前状态写入到一个Parcel对象中的。

在你的类中添加一个叫CREATOR的静态域,它要实现Parcelable.Creator接口

最后,建立一个.aidl文件声明你的parcelable类(如下面的Rect.aidl所示)

如果你使用一个定制的构建过程,不要构建.aidl文件。与C语言中的头文件类似,.aidl文件不会被编译

AIDL使用代码中的这些域和方法封装传送和解读你的对象

?

For example, here is a Rect.aidl file to create a Rect class that's parcelable:

例如,这有一个Rect.aidl文件类建立一个Rect类,它是parcelable的

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

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

这有一个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 = newParcelable.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();    }}

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类中组织传送数据是很简单的

看一下Parcel上面的其他函数,看看你可以如何将其他类型的值写入一个Parcel中。

?

Warning: Don't forget the security implications of receiving data from other processes.?

In this case, the Rect reads 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 for more information about how to keep your application secure from malware.

警告:不要忘记从其他进程接收数据的安全本质性

这种情况下,Rect从Parcel中读取4个数字,但是这取决于你要保证他们在可接收范围之内而不管调用者到底试图要做些什么

获取更多关于如何远离恶意程序保证你应用安全的更多信息,参见Security and Permissions

?

?

Calling an IPC Method

调用一个IPC方法

Here are the steps a calling class must take to call a remote interface defined with AIDL:

下面是调用步骤,调用者必须调用一个AIDL定义的远程接口

?

1.Include the .aidl file in the project src/ directory.

2.Declare an instance of the IBinder interface (generated based on the AIDL).

3.Implement ServiceConnection.

4.Call Context.bindService(), passing in your ServiceConnection implementation.

5.In your implementation of onServiceConnected(), you will receive an IBinder instance (called service).?

Call YourInterfaceName.Stub.asInterface((IBinder)service) to cast the returned parameter to YourInterface type.

6.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.

7.To disconnect, call Context.unbindService() with the instance of your interface.

1.在项目中的src目录下面导入.aidl文件

2.声明一个IBinder接口(基于AIDL生成的)的实例

3.实现ServiceConnection

4.调用Context.bindService(),传递到你的ServiceConnection实现中。

5.在你的onServiceConnected()实现中,你会收到一个IBinder实例(称为服务端)

调用YourInterfaceName.Stub.asInterface((IBinder)service)把返回值映射到YourInterface类型上面

6.调用你接口中定义的方法

你应该捕获当连接损坏时抛出的DeadObjectException异常,这是远程方法唯一会抛出的异常

7.使用你接口的实例调用Context.unbindService()来断开连接

?

A few comments on calling an IPC service:

调用IPC服务端的一些注释:

Objects are reference counted across processes.

You can send anonymous objects as method arguments.

For more information about binding to a service, read the Bound Services document.

对象跨进程时是引用计数的

你可以传递一个匿名对象作为方法的参数

更多绑定service的信息请阅读Bound Services文档

?

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

调用一个AIDL建立的服务端的一些样本代码,来自ApiDemos工程中的Remote Service样本。

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

原文地址如下,英文水平实在有限,希望拍砖同时能给予指正。

http://developer.android.com/guide/components/aidl.html

?

?

转贴请保留以下链接

本人blog地址

http://su1216.iteye.com/

http://blog.csdn.net/su1216/

热点排行