登录
首页 >  文章 >  java教程

Android文件上传卡顿怎么解决

时间:2026-02-11 13:55:10 215浏览 收藏

golang学习网今天将给大家带来《Android 文件上传卡顿原因及解决方法》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

标题:Android 文件上传卡顿问题的根源与高效解决方案

本文详解 Android 中使用 `Uri` 选择文件后上传延迟严重(长达10秒+)的根本原因,指出强行获取 RealPath 是性能毒瘤,并提供基于 `ContentResolver.openInputStream()` 的轻量级修复方案,兼容 `HttpURLConnection` 多文件异步上传,无需 Retrofit 即可实现毫秒级响应。

⚠️ 根本问题:RealPathUtil.getRealPath() 是性能黑洞

你当前代码中调用 RealPathUtil.getRealPath(context, uri) 是导致 10秒+ 延迟 的罪魁祸首。该方法通常通过遍历 MediaStore、DocumentFile 或反射 ContentProvider 实现,对某些厂商定制 ROM(如华为 EMUI、小米 MIUI)或 scoped storage 下的 content:// URI 极其低效,甚至会触发系统级权限校验或沙盒路径解析,造成主线程阻塞或 AsyncTask 启动前的长时间挂起。

更严重的是:RealPath 在 Android 10+(API 29+)已不可靠 —— Scoped Storage 强制应用只能访问自有目录或通过 Storage Access Framework (SAF) 授权的 URI,硬解 real path 不仅慢,还大概率返回 null 或错误路径,引发后续 FileInputStream 报错。

✅ 正确做法:直接使用 ContentResolver.openInputStream()

无需真实路径,直接通过 Uri 获取流。这是 Google 官方推荐、零拷贝、无权限风险、毫秒级响应的标准方式:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE && data != null) {
        Uri uri = data.getData();
        if (uri == null) return;

        // ✅ 移除所有 RealPath 相关逻辑!
        // ❌ FilePath = RealPathUtil.getRealPath(context, uri); → 删除!

        // ✅ 立即获取输入流,不阻塞
        try (InputStream is = getContentResolver().openInputStream(uri)) {
            if (is == null) {
                Toast.makeText(this, "无法读取文件", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取文件名(安全可靠)
            String fileName = getFileNameFromUri(uri);
            if (fileName == null || fileName.isEmpty()) {
                fileName = "unnamed_file";
            }

            // ✅ 立即启动上传任务(毫秒级响应)
            new UploadFile(uri, fileName).execute();

        } catch (FileNotFoundException e) {
            Toast.makeText(this, "文件不可访问", Toast.LENGTH_SHORT).show();
            Log.e("Upload", "Failed to open URI: " + uri, e);
        }
    }
}

// 安全提取文件名(适配 content:// 和 file://)
private String getFileNameFromUri(Uri uri) {
    String fileName = null;
    Cursor cursor = null;
    try {
        String[] proj = {OpenableColumns.DISPLAY_NAME};
        cursor = getContentResolver().query(uri, proj, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME);
            fileName = cursor.getString(columnIndex);
        }
    } finally {
        if (cursor != null) cursor.close();
    }
    return fileName != null ? fileName : "file";
}

? 改造 UploadFile:支持 Uri 流上传(关键!)

将 UploadFile 改为接收 Uri 和 fileName,在 doInBackground 中直接使用 openInputStream(),彻底规避 File 对象和磁盘 I/O:

@SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Boolean> {
    private final Uri fileUri;
    private final String fileName;
    private String uploadResult = null;

    UploadFile(Uri uri, String name) {
        this.fileUri = uri;
        this.fileName = name;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        DataOutputStream outputStream = null;

        try {
            String boundary = "*****" + System.currentTimeMillis() + "*****";
            String lineEnd = "\r\n";
            String twoHyphens = "--";

            URL url = new URL("https://www.example.com/fileupload1.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setUseCaches(false);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(10_000); // 10秒连接超时(合理!)
            urlConnection.setReadTimeout(30_000);      // 30秒读取超时(防卡死)

            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(urlConnection.getOutputStream());

            // 写入文件头
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"" + fileName + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
            outputStream.writeBytes(lineEnd);

            // ✅ 直接从 Uri 读取流(无 real path!)
            inputStream = getContentResolver().openInputStream(fileUri);
            if (inputStream == null) throw new IOException("Cannot open input stream for URI");

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                uploadResult = sb.toString();
                return "success".equalsIgnoreCase(uploadResult.trim());
            } else {
                // 服务器未响应或报错 → 触发本地存储
                return false;
            }

        } catch (SocketTimeoutException | ConnectException e) {
            // ✅ 网络超时/断连:立即存入 SQLite
            saveToDraftDB();
            return false;
        } catch (IOException e) {
            Log.e("Upload", "IO Error", e);
            saveToDraftDB();
            return false;
        } finally {
            if (inputStream != null) try { inputStream.close(); } catch (IOException ignored) {}
            if (outputStream != null) try { outputStream.close(); } catch (IOException ignored) {}
            if (urlConnection != null) urlConnection.disconnect();
        }
    }

    @Override
    protected void onPostExecute(Boolean success) {
        if (success && "success".equalsIgnoreCase(uploadResult)) {
            // ✅ 上传成功:移除已处理文件
            if (!mSelectedFilesList.isEmpty()) {
                mSelectedFilesList.remove(0);
            }
            // 继续上传队列中下一个(如有)
            if (!mSelectedFilesList.isEmpty()) {
                // 注意:此处需重构为队列管理,避免递归调用 AsyncTask(已废弃)
                // 建议改用 ExecutorService 或 WorkManager(见下方提示)
            }
        } else {
            // ❗ 已自动存入数据库(saveToDraftDB() 内部实现)
            Toast.makeText(ComposeActivity.this, "上传失败,已暂存草稿", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveToDraftDB() {
        // 此处插入你的 draftDB.insertDraft(...) 逻辑
        // 使用 fileUri.toString() 存储 URI 字符串(比 real path 更可靠!)
        // 后续恢复上传时,用 getContentResolver().openInputStream(Uri.parse(storedUri)) 即可
    }
}

? 关键注意事项与进阶建议

  • AsyncTask 已废弃:AsyncTask 在 Android 11+ 被标记为 @Deprecated,且 execute() 在主线程调用可能因线程池满而排队。强烈建议迁移到 ExecutorService + Future 或 WorkManager(推荐用于后台可靠上传)

  • 多文件上传请用队列:不要在 onPostExecute 中递归调用 new UploadFile().execute(),应维护一个 ConcurrentLinkedQueue,由单个 ExecutorService 顺序消费。

  • URI 比路径更持久:content:// URI 在授权有效期内始终可用(即使 App 重启),而 real path 可能失效。SQLite 中应存储 uri.toString(),而非文件路径。

  • 超时设置要合理:你原代码中 setConnectTimeout(200) 和 setReadTimeout(200) 是 200毫秒,远低于网络波动阈值,必然频繁超时。建议设为 10_000(10秒)和 30_000(30秒)。

  • Retrofit 是更优解(但非必须):虽然你坚持用 HttpURLConnection,但 Retrofit + OkHttp 自带连接池、重试、协程支持,代码量减少 70%,且天然支持 RequestBody.create(MediaType, InputStream)。若未来重构,值得投入。

✅ 总结:删除 RealPathUtil,拥抱 openInputStream() —— 这是解决“点击选择后 10 秒才开始上传”的唯一正确起点。性能提升立竿见影,且完全兼容现有 HttpURLConnection 架构。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>