一,前言:
在日常的手機應用開發(fā)過程中艘绍,經(jīng)常會遇到上傳圖片的需求赤拒,像上傳頭像之類的,這就需要調用系統(tǒng)的相機诱鞠,相冊獲取照片挎挖。但是在Android 系統(tǒng)7.0之后認為這種操作是不安全的,這篇文章主要就是記錄7.0獲取照片遇到的問題航夺。
二蕉朵,F(xiàn)ileProvider介紹
都說google官方文檔是最好的學習資料,我也帶著英語字典上來瞅了瞅阳掐。
https://developer.android.google.cn/reference/android/support/v4/content/FileProvider
1墓造,借用google官方的原話:
FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.
大致意思是說:FileProviders 是ContentProvider的子類,它通過創(chuàng)建content://Uri 來取代file:///Uri,從而有助于安全地共享與應用程序相關聯(lián)的文件锚烦。觅闽。。涮俄。詳細信息還是到google官網(wǎng)看吧
三蛉拙,拍照
1,權限申請
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2彻亲,調用系統(tǒng)相機
public void camera() {
if (hasSdcard()) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
tempFile = new File(Environment.getExternalStorageDirectory(),
PHOTO_FILE_NAME);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(
this, "com.camera.fileprovider",
tempFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
uri = Uri.fromFile(tempFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
}
}
private boolean hasSdcard() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
1>調用相機之前我們可以創(chuàng)建一個臨時文件tempFile指定拍照后原照片的位置
2>在7.0系統(tǒng)之后通過FileProvider.getUriForFile(Context context,String authority,File file);獲取content://Uri代替file:///Uri孕锄。第二個參數(shù)authority和下文將要說到的android:authorities="com.camera.fileprovider" 一致
為Uri臨時授權:
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
3>讓系統(tǒng)將原照片存放在指定的位置
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
3吮廉,在AndroidManifest.xml清單文件中注冊FileProvider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.camera.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
1>name:使用v4中默認的FileProvider
2>authorities:和上一步中獲取content://Uri保持一致。格式:xxx.fileprovider,xxx可以自定義
3>grantUriPermissions:是否允許為content://Uri賦予臨時權限
4>meta-data:配置的是我們允許訪問的文件的路徑畸肆,需要使用XML文件進行配置宦芦。name是固定寫法,resource是指定的配置的xml文件
4轴脐,在res目錄下創(chuàng)建一個名為xml的文件夾调卑,然后在該文件夾下創(chuàng)建名為provider_paths的xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_storage_root"
path="." />
<external-path
name="external_storage_root_file"
path="./Demo/" />
</paths>
具體的路徑和命名規(guī)則如下:
命名 對應目錄
<files-path name = "name" path = "path"/> Context.getFilesDir()
<cache-path name = "name" path = "path"/> Contest.getCacheDir()
<external-path name = "name" path = "path"/> Environment.getExternalStorageDirectory()
<external-files-path name = "name" path = "path"/> Context.getExternalFilesDir()
<external-cache-path name = "name" path = "path"/> Context.getExternalCacheDir()
<external-media-path name = "name" path = "path"/> Context.getExternalMediaDirs()
如果需要使用FileProvider獲取某個目錄下文件的uri,按照上表的對應關系在XML文件中聲明就可以了
5,接收相機返回的code值
if (requestCode == PHOTO_REQUEST_CAMERA && resultCode == RESULT_OK) {
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(
this, "com.camera.fileprovider",
tempFile);
} else{
uri = Uri.fromFile(tempFile);
}
crop(uri);
}
1>根據(jù)臨時文件拿到Uri
6大咱,裁剪圖片
mCropImageFile = new File(Environment.getExternalStorageDirectory(), //創(chuàng)建一個保存裁剪后照片的file
"crop_image.jpg");
// 裁剪圖片意圖
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// 裁剪框的比例恬涧,1:1
intent.putExtra("aspectX", 1); //X方向上的比列
intent.putExtra("aspectY", 1); // Y方向上的比例
intent.putExtra("outputX", 250); //裁剪區(qū)的寬度
intent.putExtra("outputY", 250); //裁剪區(qū)的高度
intent.putExtra("outputFormat", "JPEG");// 圖片格式
intent.putExtra("noFaceDetection", true);// 取消人臉識別
intent.putExtra("return-data", false); //是否在Intent中返回數(shù)據(jù)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropImageFile));
startActivityForResult(intent, PHOTO_REQUEST_CUT);
7,獲取裁剪后的圖片
if (requestCode == PHOTO_REQUEST_CUT) {
Bitmap headerBitmap = BitmapFactory.decodeFile(mCropImageFile.getAbsolutePath());
File file;
if (headerBitmap != null)
try {
file = BitmapToFile.saveFile(headerBitmap, "crop.png");
} catch (IOException e) {
e.printStackTrace();
}
try {
if (tempFile != null)
tempFile.delete();
if (mCropImageFile != null) {
mCropImageFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
四碴巾,相冊獲取照片
1咧擂,調用系統(tǒng)相冊
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
2大脉,接收系統(tǒng)相冊返回的數(shù)據(jù)
if (requestCode == PHOTO_REQUEST_GALLERY) {
// 從相冊返回的數(shù)據(jù)
if (data != null) {
// 得到圖片的全路徑
Uri uri = data.getData();
crop(uri);
}
}
1>返回的數(shù)據(jù)是Intent對像,getData()返回的就是相冊中照片存放的Uri
3塘偎,裁剪和上面的邏輯是一樣的琉历,都是根據(jù)傳入的Uri