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

效果如下:

相关推荐
雨白11 小时前
实现双向滑动的 ScalableImageView(上)
android
Y40900112 小时前
数据库基础知识——聚合函数、分组查询
android·数据库
没有了遇见17 小时前
Android 原生定位(替代高德 / 百度等三方定位)<终极版本>
android
2501_9160088918 小时前
iOS 抓包工具有哪些?全面盘点主流工具与功能对比分析
android·ios·小程序·https·uni-app·iphone·webview
2501_9159214318 小时前
iOS混淆工具实战 视频流媒体类 App 的版权与播放安全保护
android·ios·小程序·https·uni-app·iphone·webview
CYRUS_STUDIO18 小时前
LLVM 全面解析:NDK 为什么离不开它?如何亲手编译调试 clang
android·编译器·llvm
CYRUS_STUDIO18 小时前
静态分析神器 + 动态调试利器:IDA Pro × Frida 混合调试实战
android·逆向
g_i_a_o_giao21 小时前
Android8 binder源码学习分析笔记(一)
android·java·笔记·学习·binder·安卓源码分析
翻滚丷大头鱼21 小时前
android 四大组件—BroadcastReceiver
android
人生游戏牛马NPC1号21 小时前
学习 Android (二十) 学习 OpenCV (五)
android·opencv·学习