what is the use of MemoryFile in android

前端 未结 3 1453
有刺的猬
有刺的猬 2020-12-01 16:51

I want to write some bytes to a shared memory. This is done in my application1. From my another application: application2 I want to access that shared memory to read the wri

3条回答
  •  庸人自扰
    2020-12-01 17:27

    I suspect memory files don't have the getParcelFileDescriptor method. When I commented this getParcelFileDescriptor related methods and use getFileDescriptor. It worked nicely.

    import java.io.FileDescriptor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    import android.os.MemoryFile;
    
    /**
     * Invoke hidden methods using reflection
     * 
     */
    public class MemoryFileUtil {
        private static final Method sMethodGetFileDescriptor;
        static {
            sMethodGetFileDescriptor = get("getFileDescriptor");
        }
    
        public static FileDescriptor getFileDescriptor(MemoryFile file) {
            try {
                return (FileDescriptor) sMethodGetFileDescriptor.invoke(file);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    
        private static Method get(String name) {
            try {
                return MemoryFile.class.getDeclaredMethod(name);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    And created File descriptor from memory file.

    FileDescriptor fd = MemoryFileUtil.getFileDescriptor(memFile);
    

提交回复
热议问题