Android AIDL使用详解

本文详细介绍如何使用Android Interface Definition Language (AIDL) 进行Android应用内的进程间通信(IPC)。从创建.AIDL文件开始,到实现接口、绑定服务,直至客户端调用服务端方法,一步步指导读者掌握AIDL的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

aidl是 Android Interface definition language是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口

操作步骤:
(1)在 src文件夹下 创建 .aidl文件,在aidl文件定义如下:写法跟java代码类似
注:1> 它可以引用其它aidl文件中定义的接口,但是不能够引用你的java类文件中定义的接口
       2> 没有public等之类的修饰符
如:
package com.epsot.mobile.android.group.driver.aidl;
interface IRemoteGroupService {
  /** 播放完成 */
  void onPlayCompletion();
  /** 录音 */
  void onRecordVoice();
  /** 获取群组名 */
  String onGetGroupName();
}

(2)编译aidl文件,这个只要是在eclipse中开发,你的adt插件会像资源文件一样把aidl文件编译成java代码生成在gen文件夹下,不用手动去编译:编译生成 IRemoteGroupService.java如我例子中代码

(3)实现定义aidl接口中的内部抽象类 Stub,Stub类继承了Binder,并继承我们在aidl文件中定义的接口,我们需要实现接口方法,下面是我在例子中实现的Stub类:
public class RemoteGroupService extends Service
{
   @Override
   public void onCreate()
   {
      super.onCreate();
   }

   @Override
   public IBinder onBind(Intent intent)
   {
      return new RemoteGroupServiceImpl();
   }

   private class RemoteGroupServiceImpl extends IRemoteGroupService.Stub
   {
      @Override
      public String onGetGroupName() throws RemoteException
      {
         return GroupApplication.currentGroupName;
      }

      @Override
      public void onPlayCompletion() throws RemoteException
      {
      }

      @Override
      public void onRecordVoice() throws RemoteException
      {
      }
   }
}

在Androidmanifest.xml
<service android:name="com.epsot.mobile.android.group.driver.aidl.RemoteGroupService" >
    <intent-filter>
        <action android:name="com.epsot.mobile.android.group.driver.aidl.RemoteGroupService" />
        <action android:name="com.epsot.mobile.android.group.driver.aidl.RemoteGroupServiceMine" />
    </intent-filter>
</service>

(4)在要使用的地方,如:
// 创建成员变量
private IRemoteGroupService mRemoteGroupService;

// 在合适的地方创建绑定服务,一般是在 onCreate 方法中
bindService( new Intent("com.epsot.mobile.android.group.driver.aidl.RemoteGroupService" ), mRemoteNavigationServiceConntection , Context.BIND_AUTO_CREATE );

private ServiceConnection mRemoteNavigationServiceConntection = new ServiceConnection() {
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
      mRemoteGroupService = IRemoteGroupService.Stub.asInterface(service);
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
      mRemoteGroupService = null ;
  }
};

注:在同一个App中 IRemoteGroupService 可以找到,在不同的App则需要拥有相同路径名的aidl文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值