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文件中添加以下权限:


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

相关内容

热门资讯

关于透视!xpoker辅助神器... 关于透视!xpoker辅助神器!总是是真的有辅助攻略(有挂技巧)-哔哩哔哩1)xpoker辅助神器免...
分享透视!cloudpoker... 分享透视!cloudpoker作必弊!确实有辅助脚本(有挂秘笈)-哔哩哔哩1、许多玩家不知道clou...
揭露透视!竞技联盟透视!切实是... 揭露透视!竞技联盟透视!切实是真的有辅助软件(有挂技巧)-哔哩哔哩1、该软件可以轻松地帮助玩家将竞技...
关于透视!红龙poker有辅助... 关于透视!红龙poker有辅助吗!切实一直都是有辅助攻略(有挂秘籍)-哔哩哔哩1、下载好红龙poke...
详情透视!智星菠萝透视!本来一... 详情透视!智星菠萝透视!本来一直都是有辅助app(今日头条)-哔哩哔哩1、下载好智星菠萝透视脚本下载...
科普透视!pokernow辅助... 科普透视!pokernow辅助工具!原来存在有辅助方法(有挂工具)-哔哩哔哩1、很好的工具软件,可以...
曝光透视!pokemmo免费脚... 曝光透视!pokemmo免费脚本!都是是有辅助app(有挂方式)-哔哩哔哩1、pokemmo免费脚本...
了解透视!werplan透视挂... 了解透视!werplan透视挂!好像有辅助神器(有挂神器)-哔哩哔哩1、这是跨平台的werplan透...
专业透视!pokemmo修改器... 专业透视!pokemmo修改器手机版!真是是有辅助插件(真是有挂)-哔哩哔哩1、下载好pokemmo...
分享透视!epoker透视底牌... 分享透视!epoker透视底牌!切实真的有辅助插件(有挂秘诀)-哔哩哔哩1、实时epoker透视底牌...