Android-AIDL(跨进程访问

本文详细介绍了Android进程间通信(IPC)的一种方式——AIDL(Android Interface Definition Language)。包括AIDL的基本概念、如何创建和使用AIDL文件、实现接口及客户端和服务端之间的交互过程。

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

一、简介
aidl是 Android Interface definition language的缩写, 它是一种android内部进程通信接口的描述语言, 通过它我们可以
定义进程间的通信接口实现IPC
IPC:Inter-process communication :内部进程通信;
二、aidl的使用
既然aidl可以定义并实现进程通信, 那么我们怎么使用它呢?
1、创建你的aidl文件, 它的aidl文件定义如下:
package bwf.aidldemo;
import bwf.aidldemo.CarInfo;
// Declare any non-default types here with import statements
interface IMyServiceCallBack {
void callBack(String msg);
CarInfo getCarInfo();

果有bean的传递的话需要把实体类也创建一个aidl文件, 如下:
实体类要实现序列化接口, 对应的aidl文件中要指明所在包名;
2、编译你的aidl文件, Android Studio中只需要make project下即可
3、 实现你定义aidl接口中的内部抽象类Stub, Stub类继承了Binder, 并继承我们在aidl文件中定义的接口, 我们
需要实现接口方法, 下面是我在例子中实现的Stub类:
package bwf.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by Lizhangfeng on 2016/9/12 0012.
* Description:
*/
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return newMyCallBack();
/*
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
protected class MyCallBack extends IMyServiceCallBack.Stub{
@Override
public void callBack(String msg) throws RemoteException {
Log.e("tag","另外一个进程的传参为: "+msg);
@
Override
public CarInfo getCarInfo() throws RemoteException {
return newCarInfo("123","zhangsan");
}
}
4
、 在客户端调用服务端得aidl描述的接口对象
Intent intent = newIntent(this,MyService.class);
String className = getClass().getName();
// intent.setClassName("bwf.aidldemo","bwf.aidldemo.MainActivity");//跳转其他app的方式
bindService(intent, newServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
try {
callBack = IMyServiceCallBack.Stub.asInterface(iBinder);
//把数据传给service
callBack.callBack("123");
//service获取数据
CarInfo carInfo = callBack.getCarInfo();
catch (RemoteException e) {
e.printStackTrace();
}
@
Override
public void onServiceDisconnected(ComponentName componentName) {
}
},BIND_AUTO_CREATE);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值