什么是机器人的使用MemoryFile的机器人、MemoryFile

2023-09-12 07:58:32 作者:Betsy(安好)

我想写一些字节到共享内存。这是在我的应用1完成。从我的另一个应用:应用2我要访问共享内存读取写入的字节。为此,我试图使用Android的MemoryFile类。我被困如何指相同的碎片存储器之间两个不同的应用程序。我现在还混淆如果memoryFile用于相同目的或没有。 http://developer.android.com/reference/android/os/MemoryFile.html这个环节,我发现有关的话题。 提前致谢。 克里希纳

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 written bytes. For this purpose I tried using android's MemoryFile class. I am stuck as how to refer to the same shard memory between two different application. I am also now confused if memoryFile is used for the same purpose or not. http://developer.android.com/reference/android/os/MemoryFile.html this link I found regarding the topic. Thanks in advance. Krishna

推荐答案

如果你想要一些与 MemoryFile 跨进程使用,你可以使用下面的的fugly 方法:

If you want some cross-process use with MemoryFile you can use the following fugly method:

import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;

import java.io.FileDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MemoryFileUtil {
    private static final Method sMethodGetParcelFileDescriptor;
    private static final Method sMethodGetFileDescriptor;
    static {
        sMethodGetParcelFileDescriptor = get("getParcelFileDescriptor");
        sMethodGetFileDescriptor = get("getFileDescriptor");
    }

    public static ParcelFileDescriptor getParcelFileDescriptor(MemoryFile file) {
        try {
            return (ParcelFileDescriptor) sMethodGetParcelFileDescriptor.invoke(file);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    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);
        }
    }
}

你应该在看的是 #getParcelFileDescriptor(MemoryFile)方法,你可以从的ContentProvider#中openFile的实现回报(URI,字符串)