android29及以上获取视频存储位置
获取安卓设备视频位置
使用该方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
private fun createVideoOutputPath(context: Context): String {
val contentResolver = context.contentResolver
/** Represent the videos collection */
val videosCollection: Uri = sdkAndUp(29) { // if sdk is 29 or higher
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} ?: MediaStore.Video.Media.EXTERNAL_CONTENT_URI
/** Represents the data values of the video to be saved */
val contentValues = ContentValues()
// Adding the file title to the content values
contentValues.put(
MediaStore.Video.Media.TITLE,
"VID_" + System.currentTimeMillis() + ".mp4"
)
// Adding the file display name to the content values
contentValues.put(
MediaStore.Video.Media.DISPLAY_NAME,
"VID_" + System.currentTimeMillis() + ".mp4"
)
/** Represents the uri of the inserted video */
val videoUri = contentResolver.insert(videosCollection, contentValues)!!
// Opening a stream on to the content associated with the video content uri
contentResolver.openOutputStream(videoUri)
/** Represents the file path of the video uri */
val outputPath = getUriRealPath(context, videoUri)!!
// Deleting the video uri to create it later with the actual video
contentResolver.delete(videoUri, null, null)
return outputPath
}
private fun getUriRealPath(contentResolver: ContentResolver, uri: Uri): String {
var filePath = ""
val cursor = contentResolver.query(uri, null, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
var columnName = MediaStore.Images.Media.DATA
when (uri) {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI -> {
columnName = MediaStore.Images.Media.DATA
}
MediaStore.Video.Media.EXTERNAL_CONTENT_URI -> {
columnName = MediaStore.Video.Media.DATA
}
}
val filePathColumnIndex = cursor.getColumnIndex(columnName)
filePath = cursor.getString(filePathColumnIndex)
}
cursor.close()
}
return filePath
}
这段代码在MediaStore中插入了一个视频URI,检索其文件路径,并从MediaStore中删除它。
这个路径将指向Movies目录,该目录是公开的,不需要权限。
现在你可以使用这个文件路径来创建一个File对象
本文由作者按照 CC BY 4.0 进行授权