我的应用程序的一部分涉及将 png 文件保存到我的本地文件目录,然后通过内容提供商共享。
我通过 getContext().openFileOutput
写入文件
但是,在我的内容提供程序中,ParcelFileDescriptor
只会打开实际的文件对象。因此,尝试通过使用 ProviderTestCase2
的模拟内容提供程序来执行此操作时,以下代码不起作用:
return ParcelFileDescriptor.open(new File(getContext().getFilesDir(), filename), ParcelFileDescriptor.MODE_READ_ONLY)
这是因为 context.getFilesDir()
指向通过 ProviderTestCase2
代码提供给提供者的模拟上下文中的 /dev/null
.上面的代码导致异常,因为 /dev/null
不算作目录。这是预期的吗?
最佳答案
这感觉就像个笑话......文档说:
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
但是IsolatedContext源码是这样的:
@Override
public File getFilesDir() {
return new File("/dev/null");
}
所以我们最好忽略该方法并尝试使用
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
进出测试。
关于Android:提供者测试用例 2 和 getFilesDir(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796529/