【Android】外部文件存储

本文介绍了Android 11及以上版本中,应用程序如何适当地访问外部存储空间。在Android 11以前,应用可以直接使用外部存储,但在新版本中,为了保护用户空间,应用不应直接使用顶级目录。Android建议使用Context.getExternalFilesDir()来创建私有文件,或者使用getExternalStoragePublicDirectory()来访问公共文件。Android 11开始禁止应用自建外部存储的私有目录,应用应调用getExternalFilesDirs()来获取系统提供的目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要在AndroidManifest.xml的application域中添加以下字段:

android:requestLegacyExternalStorage="true"

AndroidManifest和PermissionHelp运行中都要申请权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

遇到的问题:
同一套代码APP,在Android8以下运行ok, 能够创建目录,生成文件。放到Android11上就返回false

        File Root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (!Root.exists()) {
            Root.mkdir();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = sdf.format(System.currentTimeMillis());
        Log.d("Tina", "initLog");
        if (Root.canWrite()) {
            Log.d("Tina", "Root.canWrite()");
            try {
                File logFile = new File(Root, logFileName);
                if (!logFile.exists()) {
                    Log.d("Tina", "logFile.createNewFile():  " + logFile.createNewFile());
                }
            }
        }

查询资料显示Android11不再支持访问外部存储空间:
引用连接

Applications should not directly use this top-level directory, in order to avoid polluting the user’s root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled. Other shared files should be placed in one of the directories returned by getExternalStoragePublicDirectory.

另外要参考“Android 11 中的存储机制更新”

外部存储设备上的应用专用目录
从 Android 11 开始,应用无法在外部存储设备上创建自己的应用专用目录。如需访问系统为您的应用提供的目录,请调用 getExternalFilesDirs()。

故针对Android11以上的访问存储空间需更改为:

        File Root;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        } else {
        	//此处也可以统一使用上面的目录
            Root = Environment.getExternalStorageDirectory();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值