用mediastore api不需要MANAGE_EXTERNAL_STORAGE权限。
下面的代码演示下载视频文件到手机中的Download目录。
public static boolean downloadVideo(String shareInfo, String saveToFolder, String shortUrl) {
//创建目录
FileUtils.createOrExistsDir(saveToFolder);
if (isExists(shortUrl)) {
//下载过了
return true;
}
File file = new File(saveToFolder, EncryptUtils.encryptMD5ToString(shortUrl) + ".mp4");
File fileTemp = new File(saveToFolder, EncryptUtils.encryptMD5ToString(shortUrl) + ".temp");
// Set up headers
HttpURLConnection connection = null;
try {
URL url = new URL(shareInfo);
connection = (HttpURLConnection) url.openConnection();
// Set necessary headers
connection.setRequestProperty("Host", url.getHost());
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("User-Agent", UA);
connection.connect();
} catch (IOException e) {
Log.e(TAG, "Failed to open connection", e);
if (connection != null) {
connection.disconnect();
}
return false;
}
// Download file
try (InputStream in = connection.getInputStream()) {
// Create or update media file in MediaStore
Uri mediaUri = saveMediaFile(_Context, file, in);
return mediaUri != null;
} catch (IOException e) {
Log.e(TAG, "Failed to download file", e);
return false;
} finally {
connection.disconnect();
}
}
private static void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
private static Uri saveMediaFile(Context context, File file, InputStream inputStream) {
ContentResolver contentResolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
// For Android Q and above, use MediaStore API with MediaStore.Downloads
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "");
Uri uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
if (uri != null) {
try {
// Write the content of the file to the output stream
try (OutputStream outputStream = contentResolver.openOutputStream(uri)) {
if (outputStream != null) {
copy(inputStream, outputStream);
}
}
return uri;
} catch (IOException e) {
Log.e(TAG, "Failed to write content to the output stream", e);
return null;
}
}
} else {
// For versions below Android Q, save the file directly
try {
Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
if (uri != null) {
try (OutputStream outputStream = contentResolver.openOutputStream(uri)) {
if (outputStream != null) {
copy(inputStream, outputStream);
}
}
return uri;
}
} catch (IOException e) {
Log.e(TAG, "Failed to write content to the output stream", e);
}
}
return null;
}