舒心、快乐,比什么都重要

Uri转绝对路径工具类

    /**
     * 反射从 provider uri中获取 文件绝对路径
     * @param context
     * @param uri
     * @return
     */
    private static String getProviderUriPath(Context context, Uri uri){
        String filePath = "";
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if(packs !=null){
            String fileProviderClassName = FileProvider.class.getName();
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {

                        if (uri.getAuthority().equals(provider.authority)){
                            if (provider.name.equalsIgnoreCase(fileProviderClassName)) {
                                Class<FileProvider> fileProviderClass = FileProvider.class;
                                try {
                                    Method getPathStrategy = fileProviderClass.getDeclaredMethod("getPathStrategy", Context.class , String.class);
                                    getPathStrategy.setAccessible(true);
                                    Object invoke = getPathStrategy.invoke(null, context, uri.getAuthority());
                                    if (invoke != null) {
                                        String PathStrategyStringClass = FileProvider.class.getName()+"$PathStrategy";
                                        Class<?> PathStrategy = Class.forName(PathStrategyStringClass);
                                        Method getFileForUri = PathStrategy.getDeclaredMethod("getFileForUri", Uri.class);
                                        getFileForUri.setAccessible(true);
                                        Object invoke1 = getFileForUri.invoke(invoke, uri);
                                        if (invoke1 instanceof File) {
                                            filePath = ((File) invoke1).getAbsolutePath();

                                        }
                                    }


                                } catch (NoSuchMethodException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (ClassNotFoundException e) {
                                    e.printStackTrace();
                                }

                                break;
                            }
//                            Log.e(provider);
                            break;
                        }
                    }

                }

            }

        }
        return filePath;
    }

从网上一位大神处整理而来,在此做笔记

posted @ 2022-07-26 12:05  Arcturis  阅读(223)  评论(0编辑  收藏  举报