我计划在单独进程中的 Activity 和服务之间使用共享内存,以便在它们之间传输大量内容。
为此,我阅读了我在 MemoryFile 上找到的所有信息以及如何在 Activity 之间传输它,特别是这个 stackoverflow 条目 what is the use of MemoryFile in android .
但是我无法在我的 android 版本 4.xx 上调用 getParcelFileDescriptor(使用描述的解决方案)。好像这个方法已经不存在了。
尽管如此,我还是使用以下代码将 ParcelFileDescriptor 发送到我的服务 (当成伪代码,其实是ruboto代码):
shm = MemoryFile.new("picture", 1000)
f = shm.getFileDescriptor()
p = ParcelFileDescriptor.dup( f)
b = Bundle.new()
b.putParcelable( "shm", p)
msg.setData( b)
service.send( msg)
为了测试共享内存是否可以正常访问,我在里面写了一个字符串, 并尝试在服务端检索它。
我有以下(真正的 java)代码来执行此操作:
Parcelable p = msg.getData().getParcelable("shm");
ParcelFileDescriptor shm = (ParcelFileDescriptor) p;
FileDescriptor f = shm.getFileDescriptor();
if( f.valid()) {
FileInputStream in = new FileInputStream( f);
String s = readString( in); // this fail!
}
一切正常,f 有效但我无法从收到的 fileDiscriptor 中读取,我得到: java.io.IOException:读取失败:EINVAL(无效参数)
读取代码如下:
public String readString(InputStream inputStream) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String s = r.readLine();
return s;
}
所以两个问题:
- 我做错了吗? (在任何一边)
- 或者从#getParcelFileDescriptor 截断的 MemoryFile 现在是 无法用作在两个进程之间共享内存的方法?
在后一种情况下,我看不出对这门课有任何兴趣......
我看过其他文章提到使用共享内存的 JNI 代码,但我想避免这种额外的复杂性。
最佳答案
我设法通过 MemoryFile
在应用程序之间传输数据在 Android 4.0.4 上使用 shm.getFileDescriptor()
和 ParcelFileDescriptor.dup(f)
所以,幸运的是,这个类仍然可用。在您的情况下,问题可能出在文件的内容中,尽管我不知道它如何导致 Invalid argument 错误。尝试写入和读取固定长度的字节数组而不是字符串(您实际上并没有在提供的代码中写入)并使用 InputStream.read(buffer)
简单地读取它.
关于android - class MemoryFile 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778196/