Android 11 访问 Android/data/或者getExternalCacheDir() 非root方式

前言

需求要求安装三方应用ExternalCacheDir()下载下来的apk文件。

getExternalCacheDir() : /storage/emulated/0/Android/data/com../cache/

获取访问权限

如果手机安卓版本为Android10的时候,可以在AndroidManifest.xml中添加下列代码

复制代码
   android:requestLegacyExternalStorage="true"

以此禁用分区存储,但这在Android11及以上版本不起作用。

使用 Storage Access Framework 请求访问权限。

SAF 提供了一种标准化的方式来让应用程序请求访问其他应用的文件和目录。要使用 SAF 请求访问 Android/data 目录。

复制代码
	private static int REQUEST_CODE_FOR_DIR = 10525;

    //通过SAF获取权限
 	public  void startForSAF(Activity activity) {
        Uri uri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata");
        DocumentFile documentFile = DocumentFile.fromTreeUri(activity, uri);
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        assert documentFile != null;
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, documentFile.getUri());
        activity.startActivityForResult(intent, REQUEST_CODE_FOR_DIR);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri uri;
        if (requestCode == REQUEST_CODE_FOR_DIR && (uri = data.getData()) != null) {
            getContentResolver().takePersistableUriPermission(uri, data.getFlags() & (
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
            finish();
        }
    }

    //使用时
    public static Uri pathToUri(String path) {
        return Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" +path.replace("/storage/emulated/0/", "").replace("/", "%2F"));
    }

效果如下:

相关推荐
雨白38 分钟前
加密、签名与编码
android
李新_2 小时前
【Android Bug Fix】UI不响应、异位异常排查
android·程序员
帅得不敢出门3 小时前
Android Framework定制长按电源键关机的窗口
android·java·framework
爬山算法4 小时前
MySQL(191) 如何优化MySQL的磁盘I/O?
android·数据库·mysql
深盾安全6 小时前
Kotlin Data Classes 快速上手
android
一枚小小程序员哈7 小时前
安卓\android程序开发之基于 Android 的校园报修系统的设计与实现
android
用户2018792831678 小时前
🌟 一场失败的加密舞会:SSL握手失败的奇幻冒险
android
tangweiguo030519879 小时前
面向对象编程三剑客:Dart、Java 和 Kotlin 的核心区别
android·flutter·kotlin
幼稚园的山代王10 小时前
Kotlin数据类型
android·开发语言·kotlin
xixixin_10 小时前
【H5】禁止IOS、安卓端长按的一些默认操作
android·css·ios·h5