MemoryFile 使用demo

 //A进程写数据

public static ParcelFileDescriptor writeNodeInfo(String name, AccessibilityNodeInfoTree rootNode, int[] outSize) {
        try {
            //from AccessibilityNodeInfoTree to json
            JSONObject root = new JSONObject();
            changeToJson(rootNode, root);
            //format data
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(root.toString());
            byte[] bytes = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            objectOutputStream.close();
            outSize[0] = bytes.length;
            Log.e(TAG, "writeNodeInfo, size=" + outSize[0] + ", data:" + root.toString());
            // write data
            MemoryFile memoryFile = new MemoryFile(name, bytes.length);
            memoryFile.getOutputStream().write(bytes);
            Method method = MemoryFile.class.getDeclaredMethod("getFileDescriptor");
            FileDescriptor des = (FileDescriptor) method.invoke(memoryFile);
            ParcelFileDescriptor pfd = ParcelFileDescriptor.dup(des);
            return pfd;
        } catch (Exception e) {
            Log.e(TAG, "writeNodeInfo fail: " + e);
        }
        return null;
}

//B进程读数据

public static JSONObject readNodeInfo(ParcelFileDescriptor pfd, int size) {
        try {
            //read data
            if (pfd == null) return null;
            byte[] data = new byte[size];
            FileDescriptor descriptor = pfd.getFileDescriptor();
            FileInputStream fileInputStream = new FileInputStream(descriptor);
            fileInputStream.read(data);
            //format data
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            final ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            final Object object = objectInputStream.readObject();
            final JSONObject rootNode = new JSONObject((String)object);
            byteArrayInputStream.close();
            objectInputStream.close();
            Log.e(TAG, "readNodeInfo, size=" + size + ", data:" + rootNode.toString());
            return rootNode;
        } catch (Exception e) {
            Log.e(TAG, "readNodeInfo fail: " + e);
        }
        return null;
}

A进程通过MemoryFile将数据(必须是Serializable类型数据,Parcelable不能序列化到本地)写入共享内存,然后创建对应的FileDescriptor,再将FileDescriptor转成可序列划的ParcelFileDescriptor,将此描述符通过aidl传递给B进程。B进程拿到ParcelFileDescriptor,再获取FileDescriptor,读取数据。

 

你可能感兴趣的:(android,java,json,开发语言,共享内存,android)