android 在图库中显示媒体文件

3zwtqj6y  于 2023-09-28  发布在  Android
关注(0)|答案(3)|浏览(113)

我正在从我的服务器下载文件。由于**Environment.getExternalStorageDirectory()**已弃用 * 为了提高用户隐私,直接访问共享/外部存储设备 * 我正在使用getExternalFilesDir将视频文件保存到应用文件夹(Android/data/com.myapp/Videos)。
我需要的是这个文件夹(视频)将在画廊中可见,或者文件将可见,无论哪种方式。但我的代码似乎不起作用:

val mainPath = requireActivity().getExternalFilesDir(null)!!.path + "/"
    val path = "$mainPath/Videos/clip1.mp4"

    val values = ContentValues(3)
    values.put(MediaStore.Video.Media.TITLE, "My video title")
    values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
    values.put(MediaStore.Video.Media.RELATIVE_PATH, path)
    
    requireActivity().contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
5vf7fwbs

5vf7fwbs1#

尝试以下代码并将保存的文件位置传递到此处。这将适用于图像和视频文件。它可以很好地用于视频,但对于图像,请尝试'Environment.DIRECTORY_DCIM'或'Environment.DIRECTORY_PICTURES'

fun Context.saveFileFromExternalStorageToScopedStorage(file: String): String {
    loge { "Downloaded File path: $file" }
    val lastPathSegment = file.toUri().lastPathSegment
        val sourceFile = File(file)
        var destinationDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        if (!lastPathSegment.isNullOrEmpty()) {
            if (lastPathSegment.contains(".mp4")) {
            destinationDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
            }
        }

        loge { "destinationDir: $destinationDir SourceFile isExist: ${sourceFile.exists()}" }

        
    if (sourceFile.exists() && destinationDir != null) {
        val destinationFile =File(destinationDir, "$lastPathSegment")

        try {
            FileInputStream(sourceFile).use { inputStream ->
                FileOutputStream(destinationFile).use { outputStream ->
                    val buffer = ByteArray(4 * 1024)
                    var read: Int
                    while (inputStream.read(buffer).also { read = it } != -1) {
                        outputStream.write(buffer, 0, read)
                    }
                }
            }

            // Media file copied successfully
            MediaScanner(this, destinationFile).connect()
            return destinationFile.path
        } catch (e: Exception) {
            e.printStackTrace()
            return file
        }
    return file
   }

MediaScanner类到scanFile

class MediaScanner(val mContext: Context, val file: File) : MediaScannerConnectionClient {

    private var mediaScannerConnection: MediaScannerConnection =
        MediaScannerConnection(mContext, this)

    override fun onScanCompleted(path: String?, uri: Uri?) {
        loge { "onScanCompleted: Path: $path URI: $uri" }
        mediaScannerConnection.disconnect()
    }

    override fun onMediaScannerConnected() {
        mediaScannerConnection.scanFile(file.path, null)
    }

    fun connect() {
        loge { "Connect file to scan: $file" }
        mediaScannerConnection.connect()
    }
}
uz75evzq

uz75evzq2#

下面是另一个适用于媒体文件的答案。这将显示您下载的文件到画廊。

// Function to read a media file as a string path and store it in Scoped Storage
fun saveMediaFileToScopedStorage(context: Context, mediaFilePath: String, mimeType: String): Uri? {
    val contentResolver: ContentResolver = context.contentResolver

    // Create a ContentValues object to store the file's metadata
    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, File(mediaFilePath).name)
        put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        put(
            MediaStore.MediaColumns.RELATIVE_PATH,
            if (mimeType.startsWith("image/")) Environment.DIRECTORY_PICTURES + File.separator + "yourDirectory/"
            else Environment.DIRECTORY_MOVIES + File.separator + "yourDirectory/"
        )
    }

    // Determine the appropriate MediaStore collection based on the file's MIME type
    val mediaCollection: Uri = when {
        mimeType.startsWith("image/") -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        mimeType.startsWith("video/") -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        else -> throw IllegalArgumentException("Unsupported MIME type: $mimeType")
    }

    // Insert the content values into MediaStore to create a new file
    val uri = contentResolver.insert(mediaCollection, contentValues)

    uri?.let { mediaUri ->
        try {
            // Open an InputStream to read the media file
            val inputStream = FileInputStream(mediaFilePath)

            // Open an OutputStream to write the media file to the newly created MediaStore URI
            val outputStream = contentResolver.openOutputStream(mediaUri)

            inputStream.use { input ->
                outputStream?.use { output ->
                    input.copyTo(output)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    return uri
}
omvjsjqw

omvjsjqw3#

getExternalFilesDir()中的文件不会被媒体存储扫描。
因此不会通过Gallery应用程序显示。

相关问题