Android:提供者测试用例 2 和 getFilesDir()

标签 android android-contentprovider

我的应用程序的一部分涉及将 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/

相关文章:

android - 如何填充 ListAdapter

android - 如何创建线程安全的 ContentProvider?

java - 为什么在android中命名资源不能使用大写?

Android - 如何使用内容提供者列出文件夹内的文件

android - 应用程序创建的线程如何被视为与应用程序的 ContentProvider 不同的应用程序?

自定义适配器中的 Android Dagger 2 依赖注入(inject)

android - 以编程方式触发 MediaStore 的重新扫描

android - 我无法构建我的 APK 帮助我修复它

android - 首次使用时用于用户设置的上下文菜单?

android - 如何更改操作栏选项卡 View 高度