fix(download): 适配分区存储 Uri 失效自动重建

- Android 10+ 公共目录自动转换 Uri 模式并持久化原始路径
- 增加 Uri 可写校验与 MediaStore 行失效重建逻辑
- 修复空文件路径导致的异常及线程失败异常回传问题
- 版本号升级至 3.8.18-beta-1
This commit is contained in:
tongtong committed 2026-09-08 10:11:00 +08:00
1 parent 85e0311c42
commit 96c1d26a57
10 files changed
+474 -13

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ android {
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.annotation:annotation:1.2.0'
testImplementation 'junit:junit:4.13.2'
}
@@ -16,10 +16,13 @@
package com.arialyy.aria.core.loader;
import android.net.Uri;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaConfig;
import com.arialyy.aria.core.download.DTaskWrapper;
import com.arialyy.aria.core.common.AbsNormalEntity;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.inf.IUtil;
import com.arialyy.aria.core.listener.IEventListener;
import com.arialyy.aria.core.wrapper.AbsTaskWrapper;
@@ -27,6 +30,7 @@ import com.arialyy.aria.core.wrapper.ITaskWrapper;
import com.arialyy.aria.exception.AriaException;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.UriFileUtil;
/**
* Created by lyy on 2015/8/25.
@@ -118,6 +122,12 @@ public abstract class AbsNormalLoaderUtil implements IUtil {
fail(new AriaException("下载目标(Uri 或文件路径)为空,无法启动任务"), false);
return;
}
// 分区存储 Uri 任务:启动前校验 Uri 可写性,失效时按原始路径/文件名重建 MediaStore 条目;
// 重建失败则直接失败,避免线程带着失效 Uri 发起请求后在写入阶段反复抛
// FileNotFoundException: No item at content://media/...
if (!checkUriTarget()) {
return;
}
mListener.onPre();
// 如果网址没有变,而服务器端端文件改变,以下代码就没有用了
//if (mTaskWrapper.getEntity().getFileSize() <= 1
@@ -155,6 +165,47 @@ public abstract class AbsNormalLoaderUtil implements IUtil {
return false;
}
/**
* 分区存储(Uri)任务启动前的最后一道校验:Uri 不可写时尝试按原始路径/文件名重建 MediaStore 条目;
* 重建失败则直接回调失败并终止启动(内部会调用 {@link #fail})。
*
* @return true Uri 有效(或已成功替换为可写 Uri);false 已失败终止
*/
private boolean checkUriTarget() {
if (!(mTaskWrapper instanceof DTaskWrapper)) {
return true;
}
DTaskWrapper dw = (DTaskWrapper) mTaskWrapper;
String uri = dw.getFileUri();
DownloadEntity entity =
dw.getEntity() instanceof DownloadEntity ? (DownloadEntity) dw.getEntity() : null;
// 任务恢复时瞬时变量可能为空,兜底从持久化实体恢复
if (TextUtils.isEmpty(uri) && entity != null) {
uri = entity.getFileUri();
}
if (TextUtils.isEmpty(uri)) {
return true; // 非 Uri 模式(普通文件路径任务)
}
Uri newUri = UriFileUtil.getOrRebuildWritableUri(AriaConfig.getInstance().getAPP(),
Uri.parse(uri),
entity == null ? null : entity.getFilePath(),
entity == null ? null : UriFileUtil.extractNameFromUrl(entity.getUrl()));
if (newUri == null) {
ALog.e(TAG, String.format("下载目标 Uri【%s】已失效且无法重建,任务将直接失败", uri));
fail(new AriaException(
String.format("下载目标 Uri【%s】已失效且无法重建,请删除任务后重新设置保存路径", uri)), false);
return false;
}
if (!newUri.toString().equals(uri)) {
ALog.w(TAG, String.format("任务 Uri 已由【%s】重建为【%s】", uri, newUri.toString()));
dw.setFileUri(newUri);
if (entity != null) {
entity.setFileUri(newUri.toString());
}
}
return true;
}
public boolean isStop() {
return isStop;
}
@@ -19,6 +19,7 @@ import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaConfig;
import com.arialyy.aria.core.TaskRecord;
import com.arialyy.aria.core.ThreadRecord;
import com.arialyy.aria.core.common.AbsNormalEntity;
@@ -29,6 +30,7 @@ import com.arialyy.aria.core.task.IThreadTaskAdapter;
import com.arialyy.aria.core.wrapper.AbsTaskWrapper;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.UriFileUtil;
import java.io.File;
@@ -48,14 +50,35 @@ public abstract class AbsNormalTTBuilderAdapter {
if (wrapper instanceof DTaskWrapper) {
DTaskWrapper dw = (DTaskWrapper) wrapper;
uri = dw.getFileUri();
// 兜底:任务恢复时若瞬时变量 mTempFileUri 为空,则从持久化的实体字段恢复 Uri 模式
if (TextUtils.isEmpty(uri) && dw.getEntity() instanceof DownloadEntity) {
// 兜底:任务恢复时若瞬时变量 mTempFileUri 和 mTempFilePath 均为空,则从持久化的实体字段恢复 Uri 模式
if (TextUtils.isEmpty(uri) && TextUtils.isEmpty(dw.getTempFilePath())
&& dw.getEntity() instanceof DownloadEntity) {
uri = ((DownloadEntity) dw.getEntity()).getFileUri();
}
}
if (!TextUtils.isEmpty(uri)) {
mIsUriMode = true;
mUri = Uri.parse(uri);
// 检查 Uri 有效性:不可写时尝试更换 Uri(按持久化的原始路径重建 MediaStore 行),
// 避免后续线程写入时抛 FileNotFoundException: No item at content://media/...
String restoreKey = wrapper.getEntity() instanceof DownloadEntity
? ((DownloadEntity) wrapper.getEntity()).getFilePath()
: null;
String restoreName = wrapper.getEntity() instanceof DownloadEntity
? UriFileUtil.extractNameFromUrl(((DownloadEntity) wrapper.getEntity()).getUrl())
: null;
Uri writable = UriFileUtil.getOrRebuildWritableUri(
AriaConfig.getInstance().getAPP(), mUri, restoreKey, restoreName);
if (writable == null) {
ALog.w(TAG, String.format("任务 Uri【%s】不可写或已失效且无法重建,请确认权限或 Uri 是否正确", uri));
} else if (!writable.equals(mUri)) {
mUri = writable;
((DTaskWrapper) wrapper).setFileUri(writable);
if (wrapper.getEntity() instanceof DownloadEntity) {
((DownloadEntity) wrapper.getEntity()).setFileUri(writable.toString());
}
ALog.i(TAG, String.format("任务 Uri 已由【%s】更换为可写 Uri【%s】", uri, writable.toString()));
}
} else {
String filePath = ((AbsNormalEntity) wrapper.getEntity()).getFilePath();
if (TextUtils.isEmpty(filePath)) {
@@ -72,6 +72,7 @@ public class ThreadTask implements IThreadTask, IThreadTaskObserver {
private ThreadRecord mRecord;
private String mThreadName;
private long updateInterval; // 更新间隔
private AriaException mFailException; // 保存线程任务失败的异常,用于回传上层
private Thread mConfigThread = new Thread(new Runnable() {
@Override public void run() {
@@ -101,6 +102,11 @@ public class ThreadTask implements IThreadTask, IThreadTaskObserver {
// 分区存储 Uri 模式:目标由 ContentResolver 管理,无需预创建文件
return;
}
if (getConfig().tempFile == null) {
// 防御:Uri 与本地文件同时为空时不再 new File(null),交由上层失败处理
ALog.e(TAG, "线程任务没有下载目标(Uri 与临时文件均为空),跳过文件检查");
return;
}
if (!getConfig().tempFile.exists()) {
FileUtil.createFile(getConfig().tempFile);
}
@@ -408,6 +414,7 @@ public class ThreadTask implements IThreadTask, IThreadTaskObserver {
* @param subCurrentLocation 当前子线程进度
*/
protected void fail(final long subCurrentLocation, AriaException ex, boolean needRetry) {
mFailException = ex;
if (ex != null) {
ex.printStackTrace();
}
@@ -529,6 +536,10 @@ public class ThreadTask implements IThreadTask, IThreadTaskObserver {
* 发送失败信息
*/
private void sendFailMsg(AriaException e, boolean needRetry) {
// 优先使用传入的异常,未传入时回退到 fail() 中保存的异常,避免回调到 onTaskFail 时为 null
if (e == null) {
e = mFailException;
}
Bundle b = new Bundle();
b.putBoolean(IThreadStateManager.DATA_RETRY, needRetry);
if (e != null) {
@@ -15,7 +15,10 @@
*/
package com.arialyy.aria.util;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaConfig;
import com.arialyy.aria.core.TaskRecord;
import com.arialyy.aria.core.ThreadRecord;
import com.arialyy.aria.core.common.AbsEntity;
@@ -80,16 +83,33 @@ public class DeleteDRecord implements IDeleteRecord {
return;
}
DownloadEntity entity = (DownloadEntity) absEntity;
final String filePath = entity.getFilePath();
File targetFile = new File(filePath);
// 兼容以前版本
// 兼容以前版本(m3u8 任务使用本地路径)
if (entity.getTaskType() == ITaskWrapper.M3U8_VOD
|| entity.getTaskType() == ITaskWrapper.M3U8_LIVE) {
DeleteM3u8Record.getInstance().deleteRecord(entity, needRemoveFile, needRemoveEntity);
return;
}
final String filePath = entity.getFilePath();
// 分区存储 Uri 模式:downloadPath 可能为空(旧版记录未持久化原始路径),不能执行 new File(null)。
// 此时线程/分块记录可能与其他 Uri 任务共用空 filePath,为安全起见只删除实体,并尽力删除 MediaStore 行。
if (TextUtils.isEmpty(filePath)) {
if (needRemoveFile) {
deleteMediaRow(entity);
}
String uri = entity.getFileUri();
if (TextUtils.isEmpty(uri)) {
ALog.e(TAG, "删除下载记录失败,文件路径与 Uri 均为空,无法删除任务记录");
return;
}
ALog.w(TAG, String.format("Uri 模式下载记录没有本地路径,仅删除实体记录,fileUri:%s", uri));
deleteEntityByUri(needRemoveEntity, uri);
return;
}
File targetFile = new File(filePath);
TaskRecord record = DbDataHelper.getTaskRecord(entity.getFilePath(), entity.getTaskType());
if (record == null) {
ALog.e(TAG, "删除下载记录失败,记录为空,将删除实体记录,filePath:" + entity.getFilePath());
@@ -114,12 +134,42 @@ public class DeleteDRecord implements IDeleteRecord {
deleteEntity(needRemoveEntity, filePath);
}
private void deleteEntity(boolean needRemoveEntity, String filePath){
private void deleteEntity(boolean needRemoveEntity, String filePath) {
if (needRemoveEntity) {
DbEntity.deleteData(DownloadEntity.class, "downloadPath=?", filePath);
}
}
/**
* 分区存储 Uri 模式下,实体未保存本地路径,只能按 fileUri 删除实体记录
*/
private void deleteEntityByUri(boolean needRemoveEntity, String uri) {
if (needRemoveEntity) {
DbEntity.deleteData(DownloadEntity.class, "fileUri=?", uri);
}
}
/**
* 尽力删除该 Uri 对应的 MediaStore 行(行已失效/无权限时静默失败)
*/
private void deleteMediaRow(DownloadEntity entity) {
if (entity == null || TextUtils.isEmpty(entity.getFileUri())) {
return;
}
try {
Uri uri = Uri.parse(entity.getFileUri());
if (!"content".equalsIgnoreCase(uri.getScheme())) {
return;
}
Context app = AriaConfig.getInstance().getAPP();
if (app != null && app.getContentResolver().delete(uri, null, null) > 0) {
ALog.d(TAG, String.format("删除 MediaStore 记录成功,uri:%s", uri.toString()));
}
} catch (Exception e) {
ALog.w(TAG, "删除 MediaStore 记录失败: " + e.getMessage());
}
}
/**
* 删除多线程分块下载的分块文件
*/
@@ -0,0 +1,94 @@
package com.arialyy.aria.util;
import androidx.annotation.RequiresApi;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import com.arialyy.aria.core.AriaConfig;
import java.io.File;
/**
* MediaStore 操作工具类,用于 Android 10+ 自动适配 Scoped Storage
*/
public class MediaStoreUtil {
private static final String TAG = "MediaStoreUtil";
/**
* 判定路径是否位于外部公共目录(需要使用 MediaStore)
*/
public static boolean isPublicPath(String path) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || TextUtils.isEmpty(path)) {
return false;
}
// 如果开启了 legacy 模式,则不需要转换
try {
if (Environment.isExternalStorageLegacy()) {
return false;
}
} catch (UnsupportedOperationException ignored) {
}
String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
if (!path.startsWith(extStore)) {
return false;
}
// 私有目录不需要转换
Context context = AriaConfig.getInstance().getAPP();
File extFilesDir = context.getExternalFilesDir(null);
if (extFilesDir != null) {
String parent = extFilesDir.getParent();
if (parent != null && path.startsWith(parent)) {
return false;
}
}
return true;
}
/**
* 根据文件路径获取或创建 MediaStore Uri
*/
@RequiresApi(Build.VERSION_CODES.Q)
public static Uri getOrCreateUri(Context context, String filePath) {
if (TextUtils.isEmpty(filePath)) return null;
File file = new File(filePath);
String fileName = file.getName();
String relativePath = getRelativePath(file);
Uri externalUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
// 尝试查询已存在的记录
Uri existUri = UriFileUtil.queryUriByPath(context, externalUri, filePath);
if (existUri != null && UriFileUtil.canWrite(context, existUri)) {
return existUri;
}
// 创建新记录
ContentValues values = new ContentValues();
values.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
values.put(MediaStore.Downloads.RELATIVE_PATH, relativePath);
// 默认 Android 10+ 下载任务使用 Downloads 表
try {
return context.getContentResolver().insert(externalUri, values);
} catch (Exception e) {
ALog.e(TAG, "Insert MediaStore error: " + e.getMessage());
return null;
}
}
private static String getRelativePath(File file) {
String path = file.getParent();
if (path == null) return "Download/";
String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
if (path.startsWith(extStore)) {
String relative = path.substring(extStore.length());
if (relative.startsWith("/")) {
relative = relative.substring(1);
}
return relative.endsWith("/") ? relative : relative + "/";
}
return "Download/";
}
}
@@ -15,14 +15,20 @@
*/
package com.arialyy.aria.util;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import java.io.File;
/**
* 分区存储(Scoped Storage)相关 Uri 工具类,提供文件名解析、可写性探测和权限持久化能力。
*/
@@ -52,6 +58,26 @@ public class UriFileUtil {
return "";
}
/**
* 从下载 url 中提取文件名(解码后的最后一个路径段),用于 Uri 失效时按文件名兜底重建 MediaStore 行。
*
* @return 提取失败返回 null
*/
public static String extractNameFromUrl(String url) {
if (TextUtils.isEmpty(url)) {
return null;
}
try {
String path = Uri.parse(url).getLastPathSegment();
if (TextUtils.isEmpty(path)) {
return null;
}
return java.net.URLDecoder.decode(path, "UTF-8");
} catch (Exception e) {
return null;
}
}
private static String queryDisplayName(Context context, Uri uri) {
if (!"content".equalsIgnoreCase(uri.getScheme()) || context == null) {
return null;
@@ -101,6 +127,152 @@ public class UriFileUtil {
}
}
/**
* 校验 Uri 是否可写;**不可写时尝试更换 Uri**(按原始文件路径重建)。
* <p>仅对已失效的 {@code content://media/...}(MediaStore 行,如 No item at content://media/...)
* 且 filePath 位于外部公共目录的场景自动重建:先按路径解析已存在的行,无则重新插入一行。</p>
*
* @return 可写的新 Uri;原 Uri 可写时原样返回;无法获得可写 Uri(或不属于可重建场景)返回 null
*/
public static Uri getOrRebuildWritableUri(Context context, Uri uri, String filePath) {
return getOrRebuildWritableUri(context, uri, filePath, null);
}
/**
* 校验 Uri 是否可写;**不可写时尝试更换 Uri**。
* <ul>
* <li>优先按 {@code filePath}(实体持久化的原始公共目录路径)查找/重建 MediaStore 行;</li>
* <li>若 {@code filePath} 为空(旧版 Uri 任务未持久化原始路径),则退而按 {@code displayName}
* 在 Download 目录查找/重建,使历史死记录也能自愈。</li>
* </ul>
*
* @param displayName 兜底用的文件名;不需要兜底时传 null
* @return 可写的新 Uri;原 Uri 可写时原样返回;无法获得可写 Uri(或不属于可重建场景)返回 null
*/
public static Uri getOrRebuildWritableUri(Context context, Uri uri, String filePath,
String displayName) {
if (context == null || uri == null) {
return null;
}
if (canWrite(context, uri)) {
return uri;
}
// 只有 MediaStore 的 content://media Uri 才可能因行失效而需要重建,
// 其它(FileProvider/SAF 等)Uri 无法仅凭路径重建
String scheme = uri.getScheme();
String authority = uri.getAuthority();
if (!"content".equalsIgnoreCase(scheme) || authority == null
|| !authority.startsWith("media")) {
return null;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
return null;
}
if (MediaStoreUtil.isPublicPath(filePath)) {
// 1) 优先解析已存在的 MediaStore 行
Uri exist = queryUriByPath(context, MediaStore.Downloads.EXTERNAL_CONTENT_URI, filePath);
if (exist != null && canWrite(context, exist)) {
return exist;
}
// 2) 无可用行则重新插入一行(新 Uri)
Uri created = MediaStoreUtil.getOrCreateUri(context, filePath);
if (created != null && canWrite(context, created)) {
return created;
}
}
// 3) 旧版 Uri 任务没有持久化原始路径(filePath 为空):按文件名在 Download 目录兜底查找/重建,
// 让历史死记录不再无限重试失败
if (!TextUtils.isEmpty(displayName)) {
Uri exist = queryBySelection(context, MediaStore.Downloads.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DISPLAY_NAME + "=?",
new String[]{displayName});
if (exist != null && canWrite(context, exist)) {
return exist;
}
Uri created = createDownloadUri(context, displayName);
if (created != null && canWrite(context, created)) {
return created;
}
}
return null;
}
/**
* 在系统 Download 目录插入一条 MediaStore 记录(供只有文件名、没有原始路径的旧任务兜底重建使用)
*/
private static Uri createDownloadUri(Context context, String displayName) {
if (context == null || TextUtils.isEmpty(displayName)) {
return null;
}
ContentValues values = new ContentValues();
values.put(MediaStore.Downloads.DISPLAY_NAME, displayName);
values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/");
try {
return context.getContentResolver()
.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
} catch (Exception e) {
ALog.w(TAG, "create Download uri error: " + e.getMessage());
return null;
}
}
/**
* 通过文件路径查询 MediaStore 中的 Uri
*/
public static Uri queryUriByPath(Context context, Uri contentUri, String filePath) {
if (context == null || TextUtils.isEmpty(filePath)) return null;
// 1) 优先按 _data 精确匹配
Uri uri = queryBySelection(context, contentUri,
MediaStore.MediaColumns.DATA + "=?", new String[]{filePath});
if (uri != null) return uri;
// 2) Scoped Storage 下 _data 可能不可查/已失效,按 DISPLAY_NAME + RELATIVE_PATH 匹配
File file = new File(filePath);
String displayName = file.getName();
String parent = file.getParent();
if (TextUtils.isEmpty(displayName) || TextUtils.isEmpty(parent)) return null;
String extStore = Environment.getExternalStorageDirectory().getAbsolutePath();
String relativePath;
if (parent.startsWith(extStore)) {
relativePath = parent.substring(extStore.length());
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
relativePath = relativePath.endsWith("/") ? relativePath : relativePath + "/";
} else {
relativePath = parent.endsWith("/") ? parent : parent + "/";
}
uri = queryBySelection(context, contentUri,
MediaStore.MediaColumns.DISPLAY_NAME + "=? AND "
+ MediaStore.MediaColumns.RELATIVE_PATH + "=?",
new String[]{displayName, relativePath});
if (uri != null) return uri;
// 3) 兜底仅按 DISPLAY_NAME 匹配(目录不再精确匹配)
return queryBySelection(context, contentUri,
MediaStore.MediaColumns.DISPLAY_NAME + "=?",
new String[]{displayName});
}
private static Uri queryBySelection(Context context, Uri contentUri, String selection,
String[] args) {
if (context == null || contentUri == null) return null;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(contentUri,
new String[]{MediaStore.MediaColumns._ID}, selection, args, null);
if (cursor != null && cursor.moveToFirst()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(contentUri, String.valueOf(id));
}
} catch (Exception e) {
ALog.w(TAG, "query uri error: " + e.getMessage());
} finally {
if (cursor != null) cursor.close();
}
return null;
}
/**
* 获取 Uri 对应文件的长度
*
@@ -136,6 +308,9 @@ public class UriFileUtil {
if (context == null || uri == null) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
try {
context.getContentResolver()
.takePersistableUriPermission(uri,