Android保存图片或视频到相册的最佳实践
# 业务场景
app内截图,网络下载的图片,视频 一键保存到相册
保存完后,切换到系统相册,要能立马看到
# 来源预处理
图片: 为了节省磁盘空间,需要预先压缩: 有透明度的png不压缩,无透明度的png和jpg压缩到质量85.
图片和视频均先保存到app 外部存储目录下,确保ok后,再写到系统相册,然后删除外部存储目录下的临时文件.
# 关键节点说明:
- 版本适配:核心区分 Android 10(API 29)及以上的分区存储机制与低版本的直接文件操作。
- 权限处理:低版本需显式请求存储权限,高版本依赖分区存储规则无需权限(仅允许操作特定目录)。
- 路径校验:高版本对存储路径进行合法性校验,不合法路径会被自动调整至允许目录(如 DCIM、Movies 等)。
- 媒体库同步:通过发送
ACTION_MEDIA_SCANNER_SCAN_FILE
广播通知系统更新媒体库。 - 回调机制:通过
MyCommonCallback3
返回操作结果(成功 / 失败)。
判断Android版本及存储模式:
│ │ ├─ 若 Android 10+ 且非Legacy存储 → 直接调用 writeToMediaStore()
│ │ └─ 否则(低版本或Legacy存储):
│ │ ├─ 请求 WRITE_EXTERNAL_STORAGE 和 READ_EXTERNAL_STORAGE 权限
│ │ │ ├─ 权限授予 → 调用 writeToMediaStore()
│ │ │ └─ 权限拒绝 → 回调 onError("permission denied")
writeToMediaStore():
Android 10以下逻辑:
│ │ ├─ 构建目标文件路径(外部存储+albumRelativePath+新文件名)
│ │ ├─ 确保父目录存在(创建目录,删除冲突文件)
│ │ ├─ 复制源文件到目标文件:
│ │ │ ├─ 成功且文件有效 → 广播扫描文件,回调 onSuccess(文件路径)
│ │ │ └─ 失败 → 广播扫描源文件,回调 onError("复制文件失败")
─ Android 10+ 逻辑:
│ │ │ ├─ 获取ContentResolver,解析文件MIME类型
│ │ │ ├─ 处理存储路径(albumRelativePath):
│ │ │ │ ├─ 若路径不在允许目录(DCIM/Movies/Downloads/Pictures)且不可写:
│ │ │ │ │ ├─ 图片MIME → 路径调整为 DCIM/原路径
│ │ │ │ │ ├─ 视频MIME → 路径调整为 Movies/原路径
│ │ │ │ │ └─ 其他 → 路径调整为 Downloads/原路径
│ │ │ │ └─ 否则 → 保留原路径
│ │ │ ├─ 构建ContentValues(文件名、MIME类型、相对路径)
│ │ │ ├─ 根据MIME类型选择MediaStore根URI(图片/视频/音频)
│ │ │ ├─ 插入ContentValues获取URI:
│ │ │ │ ├─ URI不为空:
│ │ │ │ │ ├─ IO线程中复制文件内容到URI输出流
│ │ │ │ │ ├─ 成功 → 广播扫描文件,回调 onSuccess(URI)
│ │ │ │ │ └─ 失败 → 回调 onError(异常)
│ │ │ │ └─ URI为空 → 回调 onError("创建MediaStore记录失败")
│ │ │
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
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
# 代码:
package com.hss.utils.enhance.media;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import androidx.annotation.NonNull;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.Utils;
import com.hss.utils.base.api.MyCommonCallback3;
import com.hss01248.permission.MyPermissions;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public class MediaStoreUtil {
public static void writeMediaToMediaStore(File finalFile,
String albumRelativePath,
MyCommonCallback3<String> callback){
writeMediaToMediaStore(finalFile,albumRelativePath,"",callback);
}
/**
*
* @param finalFile
* @param albumRelativePath allowed directories are [DCIM, Movies, Pictures]
* @param callback
*/
public static void writeMediaToMediaStore(File finalFile,
String albumRelativePath,
String newFileName,
MyCommonCallback3<String> callback) {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.Q
|| (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q
&& !Environment.isExternalStorageLegacy())){
writeToMediaStore( finalFile, albumRelativePath,newFileName,callback);
}else {
File finalFile1 = finalFile;
MyPermissions.requestByMostEffort(false, true,
new PermissionUtils.FullCallback() {
@Override
public void onGranted(@NonNull List<String> granted) {
try {
writeToMediaStore( finalFile1, albumRelativePath,newFileName,callback);
} catch (Exception e) {
LogUtils.w(e);
callback.onError(e);
//MyToast.error(e.getMessage());
}
}
@Override
public void onDenied(@NonNull List<String> deniedForever, @NonNull List<String> denied) {
callback.onError("permission denied");
}
}, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
+ File.separator + AppUtils.getAppName()+ File.separator+srcFile.getName());
} else {
contentValues.put(
MediaStore.MediaColumns.DATA,
Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+Environment.DIRECTORY_PICTURES
+ File.separator + AppUtils.getAppName()+ File.separator+srcFile.getName()
);
}*/
private static void writeToMediaStore(File srcFile,String albumRelativePath, String newFileName,MyCommonCallback3<String> callback) {
if(TextUtils.isEmpty(newFileName)){
newFileName = srcFile.getName();
}
LogUtils.d("file: "+srcFile.getAbsolutePath(),albumRelativePath,newFileName);
// 根据文件类型设置
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// 获得ContentResolver对象
ContentResolver resolver = Utils.getApp().getContentResolver();
// 设置文件信息到ContentValues对象
String name = srcFile.getName();
name = name.substring(name.lastIndexOf(".")+1).toLowerCase();
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(name);
if(mimeType ==null){
mimeType = "image/jpeg";
}
ContentValues contentValues = new ContentValues();
//判断是否已经存在,如果存在?
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, newFileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
//权限: 没有任何权限时,只有dcim,picture,movies这三个可写
if(albumRelativePath.startsWith(Environment.DIRECTORY_MOVIES)
|| albumRelativePath.startsWith(Environment.DIRECTORY_DCIM)
|| albumRelativePath.startsWith(Environment.DIRECTORY_DOWNLOADS)
||albumRelativePath.startsWith(Environment.DIRECTORY_PICTURES)){
}else {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+albumRelativePath,newFileName);
boolean canWrite = false;
if(file.exists()){
canWrite = file.canWrite();
}else {
try {
file.createNewFile();
canWrite = true;
} catch (IOException e) {
canWrite = false;
}
}
if(!canWrite){
if(mimeType.startsWith("image")){
albumRelativePath = Environment.DIRECTORY_DCIM+"/"+albumRelativePath;
}else if(mimeType.startsWith("video")){
albumRelativePath = Environment.DIRECTORY_MOVIES+"/"+albumRelativePath;
}else {
albumRelativePath = Environment.DIRECTORY_DOWNLOADS+"/"+albumRelativePath;
}
}
}
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, albumRelativePath);
//contentValues.put(MediaStore.MediaColumns.DATA, albumRelativePath);
Uri root = null;
if(mimeType.startsWith("image")){
root = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}else if(mimeType.startsWith("video")){
root = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}else if(mimeType.startsWith("audio")){
root = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}else {
LogUtils.w("mimetype is not media: ",mimeType,srcFile.getAbsolutePath());
root = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
// values.put(MediaStore.MediaColumns.IS_PENDING, 0);
//Primary directory (invalid) not allowed for content://media/external/video/media;
// allowed directories are [DCIM, Movies, Pictures]
Uri uri = resolver.insert(root, contentValues);
LogUtils.i("uri :",uri);
if (uri != null) {
ThreadUtils.executeByIo(new ThreadUtils.SimpleTask<String>() {
@Override
public String doInBackground() throws Throwable {
try (OutputStream outputStream = resolver.openOutputStream(uri);
InputStream inputStream = new FileInputStream(srcFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
inputStream.close();
outputStream.close();
Utils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
callback.onSuccess(uri.toString());
} catch (IOException e) {
LogUtils.w(e,srcFile.getAbsolutePath());
callback.onError(e);
}
return null;
}
@Override
public void onSuccess(String result) {
}
@Override
public void onFail(Throwable t) {
super.onFail(t);
callback.onError(t);
}
});
} else {
callback.onError("Failed to create new MediaStore record: "+srcFile.getAbsolutePath());
// throw new IOException("Failed to create new MediaStore record: "+srcFile.getAbsolutePath());
}
} else {
//Failed to create new MediaStore record: /storage/emulated/0/Android/data/com.hss.utilsenhance/files/Pictures/screenshot2/2024-07-09_14-50-59.jpg
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+"/"+albumRelativePath+"/"+newFileName);
LogUtils.i("file path: "+file.getAbsolutePath());
File parentFile = file.getParentFile();
if(parentFile.exists()){
if(parentFile.isFile()){
parentFile.delete();
}
}
parentFile.mkdirs();
//直接用file api写文件. uri在老版本一堆问题.
boolean copy = FileUtils.copy(srcFile, file);
//boolean copy = writeFileFromIS(file, new FileInputStream(srcFile),false,null);
LogUtils.i("file copy success: "+copy);
if(copy && file.exists() && file.length() > 0){
//然后通知mediastore扫描.
callback.onSuccess(file.getAbsolutePath());
Utils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}else {
callback.onError("copy file failed");
Utils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(srcFile)));
}
}
//java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider
// uri content://media/external/images/media from pid=5007, uid=10083
// requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()
// 插入文件到系统MediaStore
}
}
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
编辑 (opens new window)
上次更新: 2025/08/21, 15:19:48