繁体   English   中英

如何使用 MediaStore API 以正确的文件名而不是任意名称插入媒体文件到 MediaStore?

[英]How to insert media files to MediaStore using the MediaStore API insert with the proper file name instead of arbitrary name?

我正在尝试支持范围存储并尝试统一处理媒体文件的实现:成功地将媒体文件插入到 mediaStore 但使用任意名称例如:如果文件名是geeks.jpg它实际上将其创建为 ex 599345665432.jpg

fun writeImage(inputStream: InputStream, fileName: String): Uri? {
    val collectionUri = if (atLeastQ()) {
        MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
    } else {
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    }

    val imageDetails = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
        put(MediaStore.Images.Media.TITLE, fileName)
        if (atLeastQ()) put(MediaStore.Images.Media.IS_PENDING, 1)
    }

    val imageContentUri = contentResolver.insert(imageCollection, imageDetails)
    imageContentUri?.let {
        contentResolver.openOutputStream(it)?.use { outputImageFile ->
            inputStream.writeFully(outputImageFile)
        }

    if(atLeastQ()) {
         imageDetails.clear()
         imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0)
         contentResolver.update(imageContentUri, imageDetails, null, null)
      }
    }
    return imageContentUri
}

private fun atLeastQ() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q

这段代码对我来说很好,但它只适用于图片:

public void saveFileToPhone(InputStream inputStream, String filename) {
    OutputStream outputStream;
    Context myContext = requireContext();
    try {
        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.Q){
            ContentResolver contentResolver = requireContext().getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Downloads.DISPLAY_NAME,filename);
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
            Uri collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
            Uri fileUri = contentResolver.insert(collection, contentValues);
            outputStream = contentResolver.openOutputStream(Objects.requireNonNull(fileUri));
            Objects.requireNonNull(outputStream);

        }
    }catch (FileNotFoundException e) {

        e.printStackTrace();
    }
}

我建议使用SimpleStorage ,因为它会更简单:

val desc = FileDescription("geeks", "", "image/jpeg")
val media = MediaStoreCompat.createImage(this, desc, ImageMediaDirectory.PICTURES)
media?.openOutputStream()?.use { outputStream ->
    inputStream.writeFully(outputStream)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM