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

效果如下:

相关推荐
梦否2 小时前
Android 代码热度统计(概述)
android
xchenhao5 小时前
基于 Flutter 的开源文本 TTS 朗读器(支持 Windows/macOS/Android)
android·windows·flutter·macos·openai·tts·朗读器
coder_pig6 小时前
跟🤡杰哥一起学Flutter (三十五、玩转Flutter滑动机制📱)
android·flutter·harmonyos
消失的旧时光-19437 小时前
OkHttp SSE 完整总结(最终版)
android·okhttp·okhttp sse
ansondroider8 小时前
OpenCV 4.10.0 移植 - Android
android·人工智能·opencv
hsx66610 小时前
Kotlin return@label到底怎么用
android
itgather11 小时前
安卓设备信息查看器 - 源码编译
android
whysqwhw11 小时前
OkHttp之buildSrc模块分析
android
hsx66611 小时前
从源码角度理解Android事件的传递流程
android
刺客xs13 小时前
MYSQL数据库----DCL语句
android·数据库·mysql