【后台任务】Android接口定义语言(AIDL)(14)

概要


Android接口定义语言(AIDL)与您可能使用的其他IDL类似。它允许您定义客户端和服务商通过使用进程间通信(IPC)进行通信的编程接口。在Android上,一个进程无法正常访问另一个进程的内存。因此要说话,他们需要将他们的对象分解成操作系统可以理解的原语,并且为你跨越边界对象。编写代码很繁琐,因此Android会使用AIDL处理它。

注意:只有当您允许来自不同应用程序的客户端访问您的IPC服务并希望处理服务中的多线程时,才需要使用AIDL。如果您不需要在不同的应用程序执行并发IPC,你应该创建界面实现活页夹,或者,如果要执行IPC,但并不需要处理多线程,实现你的界面使用Messenger的。无论如何,确保您在实施AIDL之前了解绑定服务。

在开始设计您的AIDL接口之前,请注意对AIDL接口的调用是直接函数调用。您不应该对发生调用的线程做出假设。根据调用是来自本地进程中的线程还是远程进程,发生的情况会有所不同。特别:

  • 来自本地进程的调用在执行调用的同一线程中执行。如果这是您的主UI线程,则该线程继续在AIDL接口中执行。如果它是另一个线程,那是在服务中执行你的代码的那个线程。因此,如果只有本地线程正在访问该服务,则可以完全控制在其中执行哪些线程(但是,如果是这种情况,则根本不应该使用AIDL,而应该通过实现一个活页夹来创建接口)。
  • 来自远程进程的调用将从平台维护在您自己进程内的线程池中调度。您必须为来自未知线程的传入呼叫做好准备,同时发生多个呼叫。换句话说,AIDL接口的实现必须是完全线程安全的。
  • 该oneway关键字修改远程调用的行为。使用时,远程呼叫不会阻止; 它只是发送交易数据并立即返回。该接口的实现最终将其作为来自Binder线程池的常规调用接收为普通远程调用。如果oneway用于本地呼叫,则不会造成影响,并且呼叫仍然是同步的。

定义一个AIDL接口


您必须.aidl使用Java编程语言语法在文件中定义您的AIDL接口,然后将其保存在src/承载服务的应用程序的源代码(在目录中)以及任何其他绑定到该服务的应用程序的目录中。

当您构建包含该.aidl文件的每个应用程序时,Android SDK工具会IBinder根据该.aidl文件生成一个界面并将其保存在项目的gen/目录中。该服务必须IBinder 适当地实现接口。然后,客户端应用程序可以绑定到服务并从中调用IBinder执行IPC的方法。

要使用AIDL创建有界服务,请按照下列步骤操作:
创建.aidl文件
该文件使用方法签名来定义编程接口。

实现接口
Android SDK工具根据您的.aidl文件使用Java编程语言生成一个接口 。该接口有一个名为的内部抽象类Stub,它扩展 Binder并实现了您的AIDL接口中的方法。你必须扩展这个 Stub类并实现这些方法。

将接口公开给客户端
实现一个Service并重写onBind()以返回你的Stub 类的实现。

警告:您在第一次发布后对您的AIDL界面所做的任何更改都必须保持向后兼容,以避免打破使用您的服务的其他应用程序。也就是说,因为您的.aidl文件必须复制到其他应用程序才能访问您的服务界面,您必须保持对原始界面的支持。

创建.aidl文件
AIDL使用一种简单的语法,可以用一个或多个可以接受参数和返回值的方法声明接口。参数和返回值可以是任何类型,甚至是其他AIDL生成的接口。

您必须.aidl使用Java编程语言构建文件。每个.aidl 文件都必须定义一个接口,并且只需要接口声明和方法签名。

默认情况下,AIDL支持以下数据类型:
所有原始类型的Java编程语言(如int,long, char,boolean,等)
String
CharSequence
List
List该列表中的所有元素都必须是此列表中支持的数据类型之一或者您声明的其他AIDL生成的接口或其中一个。A List可以可选地用作“通用”类(例如 List<String>)。对方接收的实际具体类始终是一个ArrayList,尽管该方法是使用该List接口生成的。

Map
Map该列表中的所有元素都必须是此列表中支持的数据类型之一或者您声明的其他AIDL生成的接口或其中一个。通用映射(例如表单的映射 Map<String,Integer>)不受支持。对方接收的实际具体类始终是a HashMap,尽管该方法是为了使用Map接口而生成的。

您必须import为上面没有列出的每种附加类型包含一个声明,即使它们在与您的界面相同的包中定义。

定义您的服务界面时,请注意:

  • 方法可以采用零个或多个参数,并返回一个值或void。
  • 所有非基本参数都需要一个方向标签来指示数据传送的方式。或者in,out或者inout(参见下面的例子)。
    原语是in默认的,不能以其他方式。

小心:您应该将方向限制在真正需要的位置,因为编组参数很昂贵。

  • 包含在.aidl文件中的所有代码注释都包含在生成的IBinder界面中(导入和包装语句之前的注释除外)。
  • 只有方法支持; 您不能在AIDL中公开静态字段。

这是一个示例.aidl文件:

// IRemoteService.aidl
package com.example.android;

// Declare any non-default types here with import statements

/** Example service interface */
interface IRemoteService {
    /** Request the process ID of this service, to do evil things with it. */
    int getPid();

    /** Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}

只需将.aidl文件保存到项目src/目录中,并在构建应用程序时,SDK工具会IBinder在项目gen/目录中生成接口文件。生成的文件名与文件名相匹配.aidl,但带有.java扩展名(例如IRemoteService.aidl结果IRemoteService.java)。

如果您使用Android Studio,增量构建几乎立即生成联编程序类。如果你不使用Android Studio,那么下次构建应用程序时,Gradle工具会生成binder类 - 应该在完成写入文件后立即使用gradle assembleDebug (或gradle assembleRelease)构建项目.aidl,以便代码可以链接到生成的类。

2.实现接口

当您构建应用程序时,Android SDK工具会生成一个.java以您的.aidl文件命名的接口文件。生成的接口包含一个名为的子类Stub ,它是其父接口的抽象实现(例如YourInterface.Stub),并声明.aidl文件中的所有方法。

注意: Stub还定义了一些辅助方法,最值得注意的是asInterface(),它需要一个IBinder(通常是传递给客户端onServiceConnected()回调方法的方法)并返回存根接口的一个实例。有关如何进行此演员表的更多详细信息,请参阅调用IPC方法一节。

要实现从此.aidl生成的Binder接口,请扩展生成的接口(例如YourInterface.Stub)并实现从该.aidl文件继承的方法。

下面是一个使用匿名实例调用的接口的示例实现IRemoteService(由IRemoteService.aidl上面的示例定义 ):

private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
    public int getPid(){
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
        float aFloat, double aDouble, String aString) {
        // Does nothing
    }
};

现在它mBinder是Stub类(a Binder)的一个实例,它定义了服务的RPC接口。在下一步中,将向客户展示此实例,以便他们可以与服务进行交互。

在实现您的AIDL接口时,您应该注意一些规则:

  • 传入的调用不保证在主线程中执行,因此您需要从头开始考虑多线程,并将服务正确地构建为线程安全。
  • 默认情况下,RPC调用是同步的。如果您知道该服务需要超过几毫秒才能完成请求,则不应该从活动的主线程调用该服务,因为它可能会挂起应用程序(Android可能会显示“应用程序不响应”对话框) - 您应该通常从客户端中的单独线程调用它们。
  • 您抛出的任何异常都会返回给调用者。

3.将接口公开给客户

一旦你为你的服务实现了接口,你需要将它暴露给客户端,以便它们可以绑定到它。要为您的服务公开接口,请扩展Service并实现onBind()以返回实现已生成的类的实例Stub(如前一节所述)。下面是一个示例服务,将IRemoteService示例界面公开给客户端。

public class RemoteService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the interface
        return mBinder;
    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public int getPid(){
            return Process.myPid();
        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
            // Does nothing
        }
    };
}

现在,当一个客户端(如一个活动)调用bindService()连接到这个服务时,客户端的onServiceConnected()回调会接收mBinder到服务onBind() 方法返回的 实例。

客户端还必须能够访问接口类,因此如果客户端和服务位于不同的应用程序中,则客户端的应用程序必须.aidl在其src/目录中拥有该文件的副本(这会生成android.os.Binder 接口 - 为客户端提供对AIDL方法的访问)。

当客户端收到IBinder的onServiceConnected()回调,它必须调用 YourServiceInterface.Stub.asInterface(service)投返回的参数YourServiceInterface类型。例如:

IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Following the example above for an AIDL interface,
        // this gets an instance of the IRemoteInterface, which we can use to call on the service
        mIRemoteService = IRemoteService.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        mIRemoteService = null;
    }
};

有关更多示例代码,请参阅ApiDemos中的RemoteService.java类。

通过IPC传递对象


如果你有一个你想通过IPC接口从一个进程发送到另一个进程的类,你可以这样做。但是,您必须确保您的类的代码可用于IPC通道的另一端,并且您的类必须支持该Parcelable接口。支持该Parcelable接口非常重要,因为它允许Android系统将对象分解为可跨进程进行编组的基元。

要创建支持Parcelable协议的类,您必须执行以下操作:

  1. 让你的课程实现Parcelable界面。
  2. 实现writeToParcel,它采用对象的当前状态并将其写入到Parcel。
  3. CREATOR为您的类添加一个名为实现该Parcelable.Creator接口的对象的静态字段。
  4. 最后,创建一个.aidl声明你的parcelable类的Rect.aidl文件(如下面的 文件所示)。
  5. 如果您正在使用自定义构建过程,请不要将该.aidl文件添加到构建中。与C语言中的头文件类似,该.aidl文件未被编译。

AIDL在它生成的代码中使用这些方法和字段来编组和解组对象。

例如,以下是Rect.aidl创建可Rect分段类的文件:

package android.graphics;

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

这里是这个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, int flags) {
        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();
    }

    public int describeContents() {
        return 0;
    }
}

Rect班上的编组非常简单。查看其他方法Parcel以查看可以写入Parcel的其他类型的值。
警告:不要忘记从其他进程接收数据的安全隐患。在这种情况下,可以Rect从中读取四个数字Parcel,但是要确保这些值位于值的可接受范围内,无论呼叫者正在尝试执行什么操作。有关如何保护您的应用程序免受恶意软件×××的更多信息,请参阅安全和权限。

调用IPC方法


以下是调用类必须用来调用使用AIDL定义的远程接口的步骤:

  1. 将该.aidl文件包含在项目src/目录中。
  2. 声明IBinder接口的实例(基于AIDL生成)。
  3. 执行ServiceConnection。
  4. 打电话Context.bindService(),传递你的ServiceConnection实现。
  5. 在您的实施中onServiceConnected(),您将收到一个IBinder实例(称为service)。调用 将返回的参数转换为YourInterface类型。YourInterfaceName.Stub.asInterface((IBinder)service)
  6. 调用你在界面上定义的方法。您应该始终捕获 DeadObjectException连接断开时引发的异常。您还应该捕获SecurityException在IPC方法调用中涉及的两个进程具有冲突的AIDL定义时引发的异常。
  7. 要断开连接,请Context.unbindService()与您的界面实例通话。

关于调用IPC服务的几点意见:

  • 对象是跨进程的引用计数。
  • 您可以发送匿名对象作为方法参数。

有关绑定到服务的更多信息,请阅读绑定服务 文档。

下面是一些演示调用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.
            Intent intent = new Intent(Binding.this, RemoteService.class);
            intent.setAction(IRemoteService.class.getName());
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            intent.setAction(ISecondary.class.getName());
            bindService(intent, 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);
            }
        }

    };
}
Lastest Update:2018.04.24

联系我

QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ

公众号推荐:

【后台任务】Android接口定义语言(AIDL)(14)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章