You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++获取Android Download文件夹路径?安卓游戏加载mod需求

在Android C++游戏中访问Download文件夹加载Mod的可行性及路径获取方案

可行性说明

完全可行,但需适配Android不同版本的权限规则:

  • Android 10(API 29)及以上:无需申请READ_EXTERNAL_STORAGE权限,Download文件夹属于公共媒体目录,应用可直接读取其中文件
  • Android 9(API 28)及以下:必须在AndroidManifest.xml中声明READ_EXTERNAL_STORAGE权限,且在运行时请求用户授权

路径获取方法

方法1:通过JNI调用Java层API获取(推荐,兼容性更好)

先在Java层实现路径获取方法:

import android.os.Environment;

public class FileUtils {
    public static String getDownloadDirPath() {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    }
}

然后在C++层通过JNI调用该方法,拿到路径字符串:

#include <jni.h>
#include <string>

std::string getAndroidDownloadPath(JNIEnv* env) {
    jclass fileUtilsCls = env->FindClass("com/your/package/FileUtils");
    jmethodID getPathMethod = env->GetStaticMethodID(fileUtilsCls, "getDownloadDirPath", "()Ljava/lang/String;");
    jstring pathStr = (jstring)env->CallStaticObjectMethod(fileUtilsCls, getPathMethod);
    const char* pathChars = env->GetStringUTFChars(pathStr, nullptr);
    std::string path(pathChars);
    env->ReleaseStringUTFChars(pathStr, pathChars);
    env->DeleteLocalRef(fileUtilsCls);
    env->DeleteLocalRef(pathStr);
    return path;
}

方法2:C++层直接获取(依赖系统环境变量)

利用Android系统的EXTERNAL_STORAGE环境变量拼接Download路径:

#include <cstdlib>
#include <string>

std::string getDownloadPath() {
    const char* externalStorage = std::getenv("EXTERNAL_STORAGE");
    if (externalStorage == nullptr) {
        // 设备环境变量异常时,使用默认路径兜底
        return "/storage/emulated/0/Download/";
    }
    return std::string(externalStorage) + "/Download/";
}

注意事项

  • 读取文件时需处理路径拼接的正确性,避免因缺少斜杠导致路径错误
  • 要做文件存在性校验,避免加载不存在的Mod文件引发崩溃
  • 若需写入Download文件夹(比如让玩家导出Mod),Android 11及以上需申请MANAGE_EXTERNAL_STORAGE权限,仅读取则无需

内容的提问来源于stack exchange,提问作者Sean O'Connor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:29:52