Android Q的公共路径
创始人
2024-08-15 02:30:15
0

Android Q引入了Scoped Storage(作用域存储)的概念,对应用程序的访问权限进行了限制。在Android Q中,公共路径已经不再直接公开给应用程序使用,而是通过MediaStore API来访问。

以下是一个示例代码,展示如何使用MediaStore API来获取Android Q的公共路径:

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;

public class PublicPathUtils {

    private static final String TAG = "PublicPathUtils";

    public static Uri getPublicPath(Context context, String fileName) {
        Uri uri = null;
        Cursor cursor = null;
        try {
            // 查询公共图像库
            cursor = context.getContentResolver().query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.Media._ID},
                    MediaStore.Images.Media.DISPLAY_NAME + "=?",
                    new String[]{fileName},
                    null);

            if (cursor != null && cursor.moveToFirst()) {
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    // Android Q及以上版本需要使用ContentUris工具类来获取uri
                    uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
                } else {
                    // Android Q以下版本可以直接使用Uri.fromFile方法
                    uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to get public path: " + e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return uri;
    }
}

上述示例代码中,我们通过查询MediaStore.Images.Media.EXTERNAL_CONTENT_URI来获取公共图像库中指定文件名的Uri。如果是Android Q及以上版本,我们使用ContentUris工具类来构建Uri,否则可以直接使用Uri.fromFile方法。

请注意,使用MediaStore API访问公共路径需要相应的权限声明,例如在AndroidManifest.xml文件中添加以下权限:


希望这个示例代码能够帮助到您!

相关内容

热门资讯

透视资料!wejoker内置辅... 透视资料!wejoker内置辅助,wepoker究竟有没有透视(透视)确实有挂(哔哩哔哩)1、wep...
透视策略!aapoker免费透... 透视策略!aapoker免费透视脚本,We poker辅助器下载(透视)总是真的是有挂(哔哩哔哩)1...
透视项目!aapoker透视怎... 透视项目!aapoker透视怎么用,wepoker透视是真的吗(透视)真是存在有挂(哔哩哔哩)1、w...
透视窍要!wepoker有辅助... 您好,wepoker私人局有透视吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...
透视操作!pokerworld... 透视操作!pokerworld辅助器,pokemmo手机版脚本(透视)果然是真的透视技巧(哔哩哔哩)...
透视手段!pokemmo手机版... 透视手段!pokemmo手机版修改器,菠萝辅助器免费版的特点(透视)都是有挂(哔哩哔哩)1、进入到菠...
透视方针!aapoker透视怎... 透视方针!aapoker透视怎么用,aapoker脚本(透视)一直有透视技巧(哔哩哔哩)1、在aap...
透视方式!hhpoker有没有... 透视方式!hhpoker有没有外开挂,hhpoker作必弊码怎么用(透视)一直真的有透视脚本(哔哩哔...
透视要领!德扑HHpoker有... 透视要领!德扑HHpoker有挂吗,hhpoker有后台操控吗(透视)真是真的是有透视教程(哔哩哔哩...
透视演示!pokermaste... 透视演示!pokermaster修改器,hhpoker作必弊码(透视)其实是真的挂(哔哩哔哩)1、这...