FileProvider-相機(jī)相冊
最好的參考是google官網(wǎng)
一共有以下幾個步驟
1.在manifest中添加provider
<provider
android:authorities="com.mydemo.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"
/>
</provider>
- authorities 類似schema,命名空間之類梨撞,后面會用到
- name v4包中的fileprovider
- exported false表示我們的provider不需要對外開放。
- grantUriPermissions 申明為true,你才能獲取臨時共享權(quán)限。
- resource 名字隨便跟第二步有關(guān)
2.在resourse下面新建xml文件夾,然后命名為第一步中resource中的文件名字
- 例如file_paths 的代碼如下
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path name="images" path="Pictures/"/>
</paths>
- name 可以誰便填寫用來隱藏暴露出去的文件夾名字,其他應(yīng)用用name后面的名字來訪問
- path 表示當(dāng)前文件夾下面的所有文件都可以共享,
-
一定要注意Pictures后面有個"/""
- paths標(biāo)簽下面的元素必須是以下的一種或者幾種
<files-path name="name" path="path" />
對應(yīng)的文件夾是 Context.getFilesDir().
<cache-path name="name" path="path" />
對應(yīng)的文件夾是 getCacheDir().
<external-path name="name" path="path" />
對應(yīng)的文件夾是 Environment.getExternalStorageDirectory().
<external-files-path name="name" path="path" />
對應(yīng)的文件夾是 Context.getExternalFilesDir(null).
<external-cache-path name="name" path="path" />
對應(yīng)的文件夾是 Context.getExternalCacheDir().
- 如果對以上的文件夾不是很了解可以參考這個blog
- http://blog.csdn.net/u011494050/article/details/39671159
3.簡單的拍照獲取照片(先要申請權(quán)限sd卡與相機(jī)權(quán)限)
// 這里的getExternalCacheDir() 與 xml中external-cache-path 相對應(yīng)
File imagePath = new File(getExternalCacheDir(), "Pictures");
if (!imagePath.exists()){imagePath.mkdirs();}
File newFile = new File(imagePath, "mycamera.jpg");
// com.mydemo.fileprovider 為manifest重配置的 domain
Uri contentUri = FileProvider.getUriForFile(this,
"com.mydemo.fileprovider", newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
startActivityForResult(intent, 100);
4.總結(jié)
主要是通過fileprovider把file:/// Uri 替換成content:// Uri