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"));
    }

效果如下:

相关推荐
用户20187928316711 小时前
Android黑夜白天模式切换原理分析
android
芦半山11 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android
卡尔特斯12 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
ace望世界12 小时前
安卓的ViewModel
android
ace望世界12 小时前
kotlin的委托
android
CYRUS_STUDIO14 小时前
一文搞懂 Frida Stalker:对抗 OLLVM 的算法还原利器
android·逆向·llvm
zcychong15 小时前
ArrayMap、SparseArray和HashMap有什么区别?该如何选择?
android·面试
CYRUS_STUDIO15 小时前
Frida Stalker Trace 实战:指令级跟踪与寄存器变化监控全解析
android·逆向
ace望世界20 小时前
android的Parcelable
android
顾林海20 小时前
Android编译插桩之AspectJ:让代码像特工一样悄悄干活
android·面试·性能优化