将本地堆中的数据写入Android中的磁盘

问题描述 投票:0回答:1

我正在用本机代码对RGB数据进行JPEG编码,而最终的JPEG编码数据在本机字节数组中可用。将数据写入磁盘的有效方法是什么?在此输出上不再需要进行任何处理。

我可能想到的一些选择是:

  • 在Java本机边界之间复制数据,并使用标准Android方法将数据写入磁盘。
  • 用本机代码本身将数据写入磁盘。但是随着Android Q转向范围存储访问,我一直在通过MediaStore写入数据。我们可以从本地代码写入MediaStore吗?
  • 在Java代码中分配ByteBuffer,将其传递给本地代码以进行写入,然后在编码结束后,将ByteBuffer中的数据刷新到磁盘。这似乎很公平,但我宁愿在本机层中执行内存管理,而不是依赖于Java层中的GC。

我有一种很强烈的感觉,即我的某些假设是错误的,请为我的学习大声疾呼。

android memory java-native-interface
1个回答
0
投票

如果文件仅由您的应用程序使用,则可以只写到应用程序缓存(getExternalCacheDir)或数据(getExternalFilesDir)目录。

如果要使它们可被其他文件访问,则可以按照提示使用MediaStore框架。您可以将官方文档中的this example修改为以下内容:

val resolver = applicationContext.contentResolver

val imagesCollection = MediaStore.Images.Media
        .getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)

val imageDetails = ContentValues().apply {
    put(MediaStore.Images.Media.DISPLAY_NAME, "fancy_image.jpg")
    put(MediaStore.Images.Media.IS_PENDING, 1)
}

val imageContentUri = resolver.insert(imagesCollection, imageDetails)

resolver.openFileDescriptor(imageContentUri, "w", null).use { pfd ->
    int fd = pfd.getFd
    // this would be your native implementation. it should `write()` to the fd or 
    // call `fdopen` and then `fwrite`. The `use` block will automatically call 
    // `close` for you.
    native_writeFile(fd)
}

// Now that we're finished, release the "pending" status, and allow other apps
// to see the image
imageDetails.clear()
imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)
resolver.update(imageContentUri, imageDetails, null, null)
© www.soinside.com 2019 - 2024. All rights reserved.