aidl传输文件有大小1M限制,单次传输不适合传递大数据,可以使用aidl传递共享内存引用ParcelFileDescriptor方式传递图片信息。具体实现如下
一、service端
1.aidl文件IIpcService.aidl 定义,这里主要用到pfd参数
interface IIpcService {
/**
* 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 register2Server(String packageName,IIpcServiceListener ipcServiceListener);
void unregister2Server(String packageName);
String processClientRequest(String packageName,String clientRequest,inout ParcelFileDescriptor pfd);
}
2.service端 处理客户端传递的ParcelFileDescriptor ,将获取的ParcelFileDescriptor转换成Bitmap 并回调给ui层显示
public String processClientRequest(String packageName, String clientRequest, ParcelFileDescriptor pfd) {
Log.i(TAG, "processClientRequest 11 packageName:" + packageName
+ " clientRequest:" + clientRequest + " pfd:" + pfd);
String ret = clientRequest;
FileDescriptor fileDescriptor = pfd.getFileDescriptor();
FileInputStream fis = null;
try {
fis = new FileInputStream(fileDescriptor);
Bitmap rawBitmap = BitmapFactory.decodeStream(fis);
ret += " process success!";
Log.i(TAG, "processClientRequest 112 rawBitmap:" + rawBitmap + " mUiShow:" + mUiShow);
if (null != mUiShow) {
mUiShow.showBitmap(rawBitmap);
}
} catch (Exception e) {
Log.i(TAG, "processClientRequest 22 error:" + e);
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
Log.i(TAG, "processClientRequest 33 error:" + e);
}
}
Log.i(TAG, "processClientRequest 22 end ret:" + ret);
return ret;
}
二客户端
客户端连接到service后,调用接口 传递图片文件引用 ParcelFileDescriptor
String path = "/sdcard/lilei/20230207161749238.jpg";
public ParcelFileDescriptor getPfd() {
ParcelFileDescriptor pfd = null;
try {
pfd = ParcelFileDescriptor.open(new File(path), MODE_READ_WRITE);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
Log.i(TAG, "getPfd() pfd:" + pfd);
return pfd;
}
public String sendFile(String requestJson) {
Log.i(TAG, "sendFile() requestJson:" + requestJson);
if (null != mFtIpcManager) {
return mFtIpcManager.processClientRequest(requestJson, getPfd());
}
return "error";
}