`
su1216
  • 浏览: 668440 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
Group-logo
深入入门正则表达式(jav...
浏览量:71721
E60283d7-4822-3dfb-9de4-f2377e30189c
android手机的安全问...
浏览量:128448
社区版块
存档分类
最新评论

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

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/

1
1
分享到:
评论

相关推荐

    AIDL示例(Android Interface Definition Language)

    与很多其他的基于RPC的解决方案一样,Android使用一种接口定义语言(Interface Definition Language,IDL)来公开服务的接口。我们知道4个Android应用程序组件中的3个(Activity、BroadcastReceiver和...

    AIDL最简单的使用步骤

    AIDL:Android Interface Definition Language,即Android接口定义语言。 为了使其他的应用程序也可以访问本应用程序提供的服务,Android系统采用了远程过程调用(Remote Procedure Call,RPC)方式来实现。与很多其他...

    android studio下使用aidl接口传递自定义对象

    在Android开发中,有时我们需要在不同的进程间进行通信,这时我们可以使用Android Interface Definition Language (AIDL)。AIDL提供了一种机制,使得Android应用能够跨进程传递数据,包括自定义对象。本文将深入探讨...

    AndroidAIDL

    **Android AIDL(Android Interface Definition Language)详解** 在Android系统中,进程间的通信(IPC, Inter-Process Communication)是至关重要的,特别是在开发大型、复杂的应用时。AIDL(Android Interface ...

    Android服务、aidl接口demo

    在Android应用开发中,服务(Service)和AIDL(Android Interface Definition Language)是两个非常重要的组件,它们分别用于实现后台长时间运行的任务以及跨进程通信。接下来,我们将详细探讨这两个概念及其在实际...

    Android项目之AidlDemo(简单aidl的例子)

    Android项目之AidlDemo(简单的aidl的例子)。AIDL是Android中IPC(Inter-Process Communication)方式中的一种,AIDL是Android Interface definition language的缩写。需要的小伙伴自请下载。

    Android 使用AIDL进行两个APP之间通讯以及相互消息回调(一)

    AIDL:Android Interface Definition Language,翻译过来就是Android接口定义语言。是用于定义服务器和客户端通信接口的一种描述语言,可以拿来生成用于IPC的代码。所以使用AIDL需要一个服务端和客户端 作用:可以在...

    Android多进程通讯AIDL传递Parcelable对象

    AIDL(Android Interface Definition Language)是Android提供的一种接口定义语言,用于支持跨进程调用方法,从而实现多进程间的通信。 AIDL的基本原理是将接口定义为一个.aidl文件,系统会自动生成对应的Java代码...

    安卓AIDL相关-androidstudio下使用aidl接口传递自定义对象.rar

    在Android开发中,AIDL(Android Interface Definition Language)是一种强大的工具,用于实现进程间通信(IPC,Inter-Process Communication)。AIDL使得不同Android进程中的组件能够互相调用方法,即便它们运行在...

    androidstudio开发的aidl小demo

    在Android应用开发中,AIDL(Android Interface Definition Language)是一种重要的工具,用于实现跨进程通信(IPC, Inter-Process Communication)。本教程将基于"androidstudio开发的aidl小demo"来详细讲解AIDL的...

    Android应用源码之aidl跨进程调用-IT计算机-毕业设计.zip

    下面将详细介绍Android中的aidl(Android Interface Definition Language)及其在跨进程调用中的作用。 **1. AIDL简介** AIDL是Android系统提供的一种接口定义语言,用于定义两个进程间通信的接口。通过AIDL,...

    Android IPC机制之 - AIDL-TestAIDL

    AIDL(Android Interface Definition Language)是Android平台提供的一种强大的工具,专门用于实现进程间的通信。AIDL使得开发者可以定义接口,允许一个应用程序组件在另一个组件中调用方法,即使这两个组件处于不同...

    android AidlDemo(简单aidl的例子)

    在Android开发中,AIDL(Android Interface Definition Language)是一种用于进程间通信(Inter-Process Communication, IPC)的工具,使得不同应用之间的服务可以共享数据和功能。本示例"android AidlDemo(简单aidl...

    Android多进程通讯AIDLDemo

    Android Aidl(Android Interface Definition Language)是一种专门为Android系统设计的接口定义语言,它允许我们在不同的Android进程间实现安全、高效的通信。 标题"Android多进程通讯AIDLDemo"指出我们将探讨如何...

    android开发使用aidl进行跨进程通信demo

    Android Interface Definition Language(AIDL)是Android提供的一种原生接口,它允许开发者定义服务接口,使得其他进程可以调用这些服务,实现跨进程通信。本教程将深入讲解如何使用AIDL在Android开发中构建一个...

    个人练习android md5加密和aidl通信demo

    在Android开发中,MD5加密和AIDL(Android Interface Definition Language)通信是两个重要的技术概念。MD5是一种广泛使用的加密散列函数,而AIDL则是Android系统中用于进程间通信(IPC)的一种机制。 首先,让我们...

    Android的IPC与AIDL

    #### 三、AIDL(Android Interface Definition Language) **1. AIDL介绍:** AIDL是一种用于定义进程间通信接口的语言。使用AIDL可以定义一个接口文件(通常以.aidl为后缀),这个文件描述了远程接口的行为,包括...

    android aidl文件不一致引起的调用出错问题.doc

    Android AIDL(Android Interface Definition Language)是一种基于接口定义语言,用于定义 Android 应用程序之间的接口。AIDL 文件是用于定义服务端和客户端之间的接口,用于实现远程过程调用(RPC)。但是, 当...

    aidl实例代码(android开发艺术探索)

    在Android开发中,Application Interface Definition Language (简称AIDL) 是一种强大的工具,用于实现进程间的通信(IPC,Inter-Process Communication)。"aidl实例代码(android开发艺术探索)"是针对这一主题的...

    Android深入理解分析Aidl调用作业流程.docx

    Android深入理解分析Aidl调用作业流程是Android开发中的一项重要技术,Aidl(Android Interface Definition Language)是Android提供的一种接口定义语言,用于描述Android系统中服务端和客户端之间的接口。...

Global site tag (gtag.js) - Google Analytics