本小结是基于博主教程在android11上的实现。
https://blog.csdn.net/geyichongchujianghu/article/details/130045373
一、在android11上的差异(环境androidstudio2022)
- 使用AndroidStudio在创建两个 Empty View Activity 的空App:mainapp,otherapp;
- 创建aidl之前需要在build.gradle上添加下面语句
android {
......
buildFeatures{
aidl = true
}
......
}
- OtherAppMainActivity.java中关于Onclick事件中 switch–case 会报constant error。我这边百度后改为 if–else 结构。
public void onClick(View view) {
if(view.getId()==R.id.btnBindtestforaidlService) {
Log.v(TAG, "onClick():btnBindMainAppService");
bindService(mServiceIntent, this, Context.BIND_AUTO_CREATE);
}
else if(view.getId()==R.id.btnUnBindtestforaidlService) {
Log.v(TAG, "onClick():btnUnBindMainAppService");
unbindService(this);
mBinder = null;
}
}
- activity_other_app_main.xml中页面布局
我使用 androidstudio2022,这个文件是以可视化的形式展现。
注:其中layout_margin垂直和水平间隙需要填写8的倍数,否则按钮位置与填写的间隙不同。
二、传送文件描述符
由于使用aidl主要用于进程间通信,不同进程间的文件描述符关联信息是不同的,所以我在aidl中添加了传递文件描述符的接口,来验证进程间的通信。
- 添加了在aidl接口中添加了getFileDescriptor()
// IMyAidlInterface.aidl
package com.example.testforaidl;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
/**
* 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);
void setStringData(String strData);
ParcelFileDescriptor getFileDescriptor();
}
- 在mainservice中,定义了getFileDescriptor()的实现
public ParcelFileDescriptor getFileDescriptor() {
try {
// 假设这是你要传输的文件路径
File file = new File("/sdcard/temp/ren.txt");
// 打开文件得到文件描述符
ParcelFileDescriptor parcelFd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// 返回文件描述符
return parcelFd;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
注1:我事先写入helloworld!到ren.txt,然后push到设备中;
注2:ParcelFileDescriptor.open中第二个参数,如果直接填 MODE_WORLD_READABLE会报安全问题。
注3:AndroidManifest.xml 中添加读写文件的权限
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- 在客户端java中添加了调用
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (mBinder == null) {
mBinder = IMyAidlInterface.Stub.asInterface(iBinder);
mICount++;
Log.v(TAG, "onServiceConnected() 第 " + mICount + " 次");
try {
String strData = "第" + mICount + "次连接Service成功!";
mBinder.setStringData(strData);
ParcelFileDescriptor parcelFd = mBinder.getFileDescriptor();
try {
readstring(parcelFd);
}catch (IOException e) {
e.printStackTrace();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
public void readstring(ParcelFileDescriptor parcelFd ) throws IOException {
FileDescriptor fileDescriptor = parcelFd.getFileDescriptor();
FileInputStream fis = new FileInputStream(fileDescriptor);
byte[] bytes = new byte[20];
int len1 = fis.read(bytes);
String s1 = new String(bytes);//把字节数组转换成字符串
Log.v(TAG,s1);
}