若是本文幫助到你,本人不勝榮幸,若是浪費了你的時間,本人深感抱歉。 但願用最簡單的大白話來幫助那些像我同樣的人。若是有什麼錯誤,請必定指出,以避免誤導你們、也誤導我。 本文來自:www.jianshu.com/users/320f9… 感謝您的關注。android
在一個項目中忽然看到了以下的代碼,就很好奇這個東西是這麼用的。而後搜了搜,也沒發現什麼講這個東西的。緩存
官方是這樣說的 :FileProvider 是一個特殊的 ContentProvider 的子類,它使用 content:// Uri 代替了 file:/// Uri. ,更便利並且安全的爲另外一個app分享文件。安全
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.android.ted.gank.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths"/>
</provider>
複製代碼
官方也提供了一個很是簡單的例子:app
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<permission
android:name="com.example.myapp..ACCESS_UPDATE_RESULT"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.myapp.ACCESS_UPDATE_RESULT"/>
<application
...>
<!--在這裏定義共享信息-->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
複製代碼
注意要添加權限 咱們能夠看到在<meta-data中,定義了一個資源路徑,而後就是第二步ide
<paths>
<files-path path="images/" name="myimages" />
</paths>
複製代碼
在這個文件中,爲每一個目錄添加一個XML元素指定目錄。 paths 能夠添加多個子路徑: 分享app內部的存儲; 分享外部的存儲; 分享內部緩存目錄。(我遇到的就是分享的緩存)spa
其中屬性的意思: path=「images/」 就是你所要共享的文件路徑。 name="myimages" 就是告訴FileProvider 用 myimages 添加進URIs 內容字段去訪問 files/images/ 的子目錄。code
content://com.example.myapp.fileprovider/myimages/default_image.jpg
複製代碼
能夠看到: com.example.myapp.fileprovider:前面是咱們在AndroidManifest.xml中指定的; myimages:是咱們指定的 name; default_image.jpg:就是咱們想要訪問的圖片了。cdn
例如,我看到到這個項目,分享的是緩存路徑下的圖片,而後用Uri讓系統的壁紙來打開本身項目的圖片。xml
//獲得緩存路徑的Uri
Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.android.ted.gank.fileprovider", file);
//壁紙管理的意圖
Intent intent = WallpaperManager.getInstance(getActivity()).getCropAndSetWallpaperIntent(contentUri);
//開啓一個Activity顯示圖片,能夠將圖片設置爲壁紙。調用的是系統的壁紙管理。
getActivity().startActivityForResult(intent, ViewerActivity.REQUEST_CODE_SET_WALLPAPER);
複製代碼
若是哪裏有什麼問題,請必定批評指正。blog