如何从相机拍照建立的Fileprovider中获取绝对路径
阅读原文时间:2023年07月05日阅读:1

我们通过高版本获取的fileprovider,然后拍了个照片,如下

imageUri = FileProvider.getUriForFile

但是我们发现当我们

        File file = new File(imgeUri);

这样建立文件时,就会报fileNotfound的io异常

为什么呢,因为我们发现imageUri是给我们返回的是content:/开头的这样的路径,显然是无法直接访问的

下面通过这个方法访问

private String getProviderUriPath(Uri uri){  
    String filePath = "";  
    List<PackageInfo> packs = this.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, this, 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;  
}

希望能帮到大家

原博主 文章地址 @https://blog.csdn.net/zswqaxcde/article/details/79205526