Android使用AIDL+MemoryFile传递大数据

Android进程间通信经常会使用AIDL,简单方便,但是数据量有限制,超过一定值会报错:

 E  !!! FAILED BINDER TRANSACTION !!!  (parcel size = 2073744)

可以通过使用AIDL+MemoryFile传递大数据


新建AIDL接口:
interface OnFileListener{
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void onFile(in ParcelFileDescriptor file);
}

添加监听接口

 void addFileListener(OnFileListener listener);

服务端发送数据

 MemoryFile imageFile = new MemoryFile(System.currentTimeMillis()+"image.data",image.length);
 imageFile.writeBytes(image,0,0,image.length);
 ParcelFileDescriptor pfd = getParcelFileDescriptor(imageFile);
 if (pfd!=null){
      listener.sendFile(pfd);
 }
 
 fun getParcelFileDescriptor(memoryFile: MemoryFile): ParcelFileDescriptor? {
        return try {
            val method: Method = MemoryFile::class.java.getDeclaredMethod("getFileDescriptor")
            method.setAccessible(true)
            val fd: FileDescriptor = method.invoke(memoryFile) as FileDescriptor
            ParcelFileDescriptor.dup(fd)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

客户端接收数据

			service.addFileListener(new OnFileListener.Stub() {
                    @Override
                    public void onFile(ParcelFileDescriptor pfd) throws RemoteException {
                        try {
                            FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            byte[] buf = new byte[1920*1080];
                            int len;
                            while ((len = fis.read(buf)) != -1) {
                                bos.write(buf, 0, len);
                            }                      
                            bos.close();
                            fis.close();
                            pfd.close();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });

实测实时传递Camera数据比较流畅

你可能感兴趣的:(android)