Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of MemoryFile in android

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

like image 462
nits.kk Avatar asked Nov 17 '11 09:11

nits.kk


1 Answers

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

What you should be looking at is the #getParcelFileDescriptor(MemoryFile) method which you can return from an implementation of ContentProvider#openFile(Uri, String).

like image 113
Jens Avatar answered Sep 16 '22 15:09

Jens