AIDL

本文介绍如何通过AIDL实现Android服务端与客户端的交互,包括定义接口、实现服务端Service、客户端绑定及调用方法等步骤。

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

在接口文件AIDLFunctions.aidl中,我们定义一个方法 show

interface AidlFunctions{
void show();
}
服务端:
AIDL的使用,需要一个Service配合,所以我们在服务端还要声明一个Service

public class AIDLService extends Service {
//stub就是系统自动产生的
AidlFunctions.Stub binder;

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
binder = new AidlFunctions.Stub() {

@Override
//这里是我们在接口中声明的方法的实现
public void show() throws RemoteException {
// TODO Auto-generated method stub
System.out.println("--------------------收到----------------------");
}
};
return binder;
}
}
在AndroidManifest声明Service

<service android:name="com.example.androidaidl.AIDLService">
<intent-filter>
<action android:name="com.example.androidaidl.AIDLService" />
</intent-filter>
</service>
客户端:

//绑定服务,要用到ServiceConnection
private ServiceConnection serviceConnection;
//自定义的接口,和服务端一样
private AidlFunctions aidlFunctions;

serviceConnection = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
System.out.println("--------------------ServiceDisconnected----------------------");
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
System.out.println("--------------------ServiceConnected----------------------");
aidlFunctions = AidlFunctions.Stub.asInterface(service);
}
};
Intent intent = new Intent("com.example.androidaidl.AIDLService");
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
//调用show方法
try {
aidlFunctions.show();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值