android 7.0获取文件路径(非相机图片路径)

近来项目要求利用智能眼镜拍照然后上传图片到服务器的需求,本来以为很简单和调用系统相机获取图片路径一样的,结果是我太年轻了,网上搜罗一大堆全是系统相机图片的路径的获取方法。折腾好久终于弄出来了,献给有需要的同行。不多说直接贴代码:

public static String getFilePathByUri(Context context, Uri uri) {
    String path = null;
    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) {
                                        path = ((File) invoke1).getAbsolutePath();
                                    }
                                }
                            } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }

                            break;
                        }
                        break;
                    }
                }

            }

        }
    }
    return path;
}

感谢android_郑提供的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值