Android学习--Service之AIDL

本文深入探讨了Android中进程间通信(IPC)的实现方式——AIDL,包括如何定义、实现和调用AIDL接口,以及如何通过AIDL传递对象。重点介绍了AIDL接口的创建、实现步骤,以及如何在服务端与客户端之间建立通信。同时,文章还详细阐述了如何在IPC中传递类对象,需遵循的规则以及如何捕获异常。
概述

    AIDL:Android Interface Definition Language.
    通常情况下,在Android中,一个进程是无法访问另一个进程的内存空间的;如果要实现此功能,就需要把对象解码成操作系统能够理解的原始字节,然后才能跨进程传送,AIDL就是用来完成这项工作的。
    注意,只有service需要与其他应用进行IPC、并且需要处理多线程任务时,才需要使用AIDL。(如果service不需要进行IPC,可以通过继承Binder实现对外接口;如果需要进行IPC 、但是不需要处理多线程任务,可以使用Messenger实现对外接口。)

  
定义AIDL接口

       AIDL的接口要定义在后缀名为.aidl的文件中,并把该文件保存在持有该service、及打算绑定该service的应用程序的src/文件夹下。在应用程序中创建了.aidl文件后,Android SDK会在此.aidl文件的基础上自动生成一个IBinder接口(此接口的代码存放在工程gen/文件夹下)。在service端,必须在适当的时候实现此IBinder接口;在客户端,可以通过此IBinder与service进行IPC(在客户端不用具体实现此IBinder接口)。
    创建包含AIDL功能的service,步骤如下:
    1、创建.aidl文件:在此文件中定义包含函数签名的编程接口;
    2、实现接口:第一步完成后,Android SDK会基于.aidl文件生成一个相应的接口,此接口有一个名字为Stub的抽象内部类(该类继承了Binder并且抽象实现了AIDL接口);必须在service中继承此Stub内部类并实现其内部的函数。
    3、将此接口暴露给客户:实现Service并在其onBind()方法中返回Stub的实现。
   
    现将各步骤详细介绍如下
    1、创建.aidl文件
    必须用Java语言创建.aidl文件;每个.aidl文件中只能定义一个接口,并且里面只包含接口的声明和方法的签名。
    .aidl文件中可以使用任何数据类型(主要用于方法的参数和返回值),甚至其他AIDL生成的接口;但是,AIDL默认支持的只有以下数据类型(对于其他类型必须import引入):
    *Java中所有的基本数据类型,及String、ChaSequence;
    *List:List里包含的必须是此处列举的数据类型、其他AIDL生成的接口、或声明的Parcelable。可以使用泛类型(如List<String>);即使函数中使用的是List接口,在实体类中实际接收到的通常为ArrayList。
    *Map:Map里包含的必须是此处列举的数据类型、其他AIDL生成的接口、或声明的Parcelable。不支持泛型Map;即使函数中使用的是Map接口,在实体类中实际接收到的通常为HashMap。
    创建.aidl文件时的注意事项:
    *里面的方法可以接收0或多个参数,可以有返回值或返回void;
    *所有的非基本类型的参数需要一个定向标签(in、out或inout),指示数据的去向;基本数据类型默认只能是in。(下面示例代码中未见到此标签的使用,不理解其具体作用。)
    *.aidl文件中所有的注释都会被包含在生成的IBinder接口中(除了import和package语句前的注释);
    *与普通interface不同的是,AIDL中不能包含静态域。
    下面一个.aidl文件的示例:

// IRemoteService.aidl
package com.example.android;
// 在此import非默认支持的数据类型 
/** 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);
}

    把此文件保存在工程的ser/文件夹下,然后SDK工具就会自动在gen/文件夹下生成相应的IBinder接口文件;两个文件的名称相同,后缀不同,前者为.aidl,后者为.java。
    2、实现接口
    在完成上面一步之后,SDK工具自动生成了一个接口文件,此文件中有一个内部抽象类Stub,它继承了Binder并抽象实现了父类接口;所谓"实现接口"就是要实现此Stub类。
    示例代码如下:(使用了匿名机制,实际上包含了实现Stub类、并创建其实例两个过程)

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就是一个Binder实例(因为Stub继承了Binder),是客户端跟service通信的桥梁。
    实现AIDL接口的注意事项:
    *要考虑多线程的问题,确保service是线程安全的;
    *默认情况下,RPC(远程进程调用)是同步的,如果service需要较长时间完成对请求的响应,就不应该在activity的主线程内调用该service;应该在客户端另起一个线程来调用此service,以避免ANR;
    *无法向客户端抛异常。
    3、向客户端暴露接口
    即实现service的onBind()方法,并返回Stub的实例。
    示例代码如下:

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()绑定此service时,会在客户端的onServiceConnected()方法中得到由onBind()返回的mBinder;在onServiceConnected()方法中要记得调用Stub的asInterface()方法,对得到的IBinder对象进行类型转化。示例代码如下:

IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        // 将IBinder向下转型为IRemoteService(因为此处的IBinder实际类型为Stub,而Stub实现了IRemoteService接口,所以可以转型成功) 
        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;
    }
};

    当然,客户端必须拥有Stub抽象类的访问权;因此,如果客户端与service不在同应用程序中(通常如此),必须把上面创建的.aidl文件复制到客户端的ser/文件夹下,这样SDK工具会同样在客户端生成AIDL接口,客户端就可以使用Stub的方法了。

通过IPC传递对象

    可以在IPC间传递类对象,但是此类需要实现Parcelable接口,并且要确保IPC的另一端拥有此类的源代码。
    创建支持Parcelable协议的类的步骤如下:
    1、让类实现Parcelable接口;
    2、实现Parcelable的writeToParcel()方法,此方法用于把当前类写进Parcel;
    3、添加一个实现了Parcelable.Creator接口、名称为CREATOR的域;
    4、创建一个.aidl文件,在其中声明此类是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类是parcelable的:

package android.graphics;
// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;//注意此处的parcelable为小写
调用IPC另一端的方法

    要调用AIDL中定义的远程接口中的方法,客户端需要完成以下几步:
    1、在ser/文件夹下包含相应的.aidl文件,系统会基于此文件生成包含IBinder接口的文件;
    2、声明上述IBinder接口类型的成员变量;(不用初始化,赋值操作在下述的onServiceConnected()中完成)
    3、实现ServiceConnection;
    4、调用Context.bindService(),并把ServiceConnection的实例传递给这个函数;
    5、之后会在ServiceConnection的onServiceConnected()方法中得到一个IBinder对象,要记得调用AIDL接口中的asInterface()方法对其进行类型转化。
    6、接下来就可以通过得到的IBinder对象调用远程接口中的方法了,但是此时一定要记得捕获DeadObjectException(此异常会在连接意外中断时抛出,是由远程方法抛出的唯一异常);
    7、要解除绑定,调用Context.unbindService()。
    还有以下两点需注意:
    *Objects are reference counted across processes.
    *可以向函数传递匿名对象。
    示例代码如下:

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

    };
}

此部分的所有示例代码均节选自官方的APIDemos中的Remote Service示例

<think>好的,我现在需要解决用户提到的Android硬件GNSS AIDL服务崩溃的问题,具体错误是“qti agnssServiceDied IAGnss AIDL service died”。首先,我需要了解这个错误发生的背景和可能的原因。 根据用户提供的引用信息,尤其是引用[1]中提到的关于HIDL和VINTF清单的内容,我推测这个问题可能与HIDL服务的管理或VINTF清单的配置有关。可能涉及到服务注册、Binder通信或者依赖库的问题。此外,引用[2]提到了GnssLocationProvider的native方法,可能涉及到GNSS服务的底层实现或JNI调用问题。 接下来,我需要考虑常见的导致AIDL服务崩溃的原因,比如服务未正确注册、Binder通信超时、权限问题、资源泄漏或底层驱动故障。同时,用户提到的错误信息中提到了“qti agnssServiceDied”,这可能表明服务在运行时发生了未处理的异常,或者依赖的组件未能正确初始化。 根据引用[1]中的VINTF清单相关错误,还需要检查Android.bp或相关构建文件是否正确引用了VNDK库,避免类似“extends属性引用非VNDK库”的错误。此外,查看日志中的堆栈跟踪信息可以帮助定位崩溃的具体位置,比如是否是Binder事务失败、内存溢出或权限不足。 可能的解决步骤包括: 1. 检查服务注册:确认AIDL服务在manifest中正确声明,并且服务类正确继承自生成的Stub类。 2. 查看日志:通过adb logcat获取详细错误日志,过滤关键字如“IAGnss”、“AIDL”、“Died”等,确定崩溃点。 3. 权限检查:确保服务需要的权限(如位置权限、Binder权限)已在AndroidManifest.xml中声明。 4. 依赖库验证:确保所有依赖的HIDL或AIDL接口库版本兼容,VINTF清单正确配置。 5. 资源管理:检查是否有内存泄漏或资源未释放的情况,尤其是在JNI层或原生代码中。 6. 更新驱动或固件:如果是硬件相关的问题,可能需要更新GNSS模块的驱动或固件。 另外,用户提到的错误可能涉及到供应商特定的实现(如qti),因此需要参考供应商提供的文档或支持资源,确认是否有已知的问题或补丁。如果服务崩溃发生在回调方法中,可能需要确保回调接口的实现是线程安全的,并且正确处理了异常情况。 最后,建议用户尝试复现问题,并在崩溃时收集完整的logcat输出,以便更精确地定位问题根源。如果问题依然存在,可能需要深入调试服务的生命周期或与底层HAL层的交互。</think>### IAGnss AIDL服务崩溃的解决方案 #### 1. **检查服务注册与绑定逻辑** - **服务声明**:确保AIDL服务在`AndroidManifest.xml`中正确注册,例如: ```xml <service android:name=".QtiAGnssAidlService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.hardware.gnss.IAGnss/default"/> </intent-filter> </service> ``` 若未正确声明服务路径或接口名称,会导致服务无法被系统发现[^1]。 - **Binder连接**:在客户端绑定服务时,需检查`ServiceConnection`是否正确处理绑定状态: ```java private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { iAGnss = IAGnss.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { iAGnss = null; // 触发重连或错误处理 } }; ``` #### 2. **分析日志定位崩溃点** - 通过`adb logcat`过滤关键字(如`IAGnss`、`AIDL`、`Died`),例如: ``` adb logcat | grep -E 'IAGnss|AIDL|Binder|Died' ``` - **常见错误类型**: - **Binder事务失败**:若日志显示`DeadObjectException`,表明Binder通信中断,可能是服务端崩溃或未响应。 - **权限不足**:检查是否缺少`android.permission.ACCESS_FINE_LOCATION`或`android.permission.LOCATION_HARDWARE`权限[^2]。 - **原生层崩溃**:若日志包含`signal 11 (SIGSEGV)`,可能是JNI或HAL层内存越界或空指针。 #### 3. **验证VINTF清单与依赖库** - 在`Android.bp`或`Android.mk`中,确保依赖的库(如`libhidltransport`)标记为VNDK,避免构建错误: ```makefile vndk: { enabled: true, } ``` 引用非VNDK库会导致服务无法在供应商分区加载。 #### 4. **服务端代码健壮性检查** - **异常捕获**:在AIDL接口实现中,添加`try-catch`块处理潜在异常: ```java @Override public void setCallback(IAGnssCallback callback) throws RemoteException { try { // 业务逻辑 } catch (Exception e) { Log.e(TAG, "setCallback failed", e); } } ``` - **资源释放**:若涉及JNI层操作(如GNSS天线信息获取),需确保及时释放内存: ```cpp extern "C" JNIEXPORT void JNICALL Java_com_example_GnssNative_releaseResources(JNIEnv* env, jobject thiz) { if (gnssAntennaInfo != nullptr) { delete gnssAntennaInfo; gnssAntennaInfo = nullptr; } } ``` #### 5. **更新驱动与固件** - 联系硬件厂商确认GNSS模块固件版本,并更新到最新版本。部分崩溃可能由芯片驱动缺陷引起。 #### 6. **调试工具辅助** - 使用`ndk-stack`分析原生层崩溃: ``` adb logcat | ndk-stack -sym /path/to/so ``` - 启用AIDL详细日志: ``` adb shell setprop log.tag.Aidl V ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值