Android 7.0實現拍照、獲取相簿圖片上傳頭像功能
阿新 • • 發佈:2019-01-24
對網上關於Android7.0的上傳頭像進行整理
1.新增許可權管理。內容例如以下:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
2.在manifest中新增provider。內容例如以下:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.jph.takephoto.fileprovider" android:grantUriPermissions="true" android:exported="false"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
exported:要求必須為false,為true則會報安全異常。grantUriPermissions:true,表示授予 URI 暫時訪問許可權。
3.為了指定共享的資料夾我們須要在資源(res)資料夾下建立一個xml資料夾,然後建立一個名為“file_paths”(名字能夠隨便起,僅僅要和在manifest註冊的provider所引用的resource保持一致就可以)的資原始檔。內容例如以下:
xml version="1.0" encoding="utf-8"?> <resources> <paths> <external-path path="" name="camera_photos" /> </paths> </resources>
上述程式碼中path=”“,是有特殊意義的,它程式碼根資料夾。也就是說你能夠向其它的應用共享根資料夾及其子資料夾下不論什麼一個檔案了,假設你將path設為path=”pictures”,
那麼它代表著根資料夾下的pictures資料夾(eg:/storage/emulated/0/pictures),假設你向其它應用分享pictures資料夾範圍之外的檔案是不行的。
4.上述準備工作做完之後,如今我們就能夠使用FileProvider了。內容例如以下:
private void setupDialog(){ final String[] items = {"拍照", "相簿"}; AlertDialog.Builder listDialog = new AlertDialog.Builder(context); listDialog.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0){ camera(); }else if (i == 1){ gallery(); } } }); listDialog.show(); } private void gallery(){ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, REQUEST_GALLERY); } private void camera(){ Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getPackageManager()) != null) { mTmpFile = new File(FileUtils.createRootPath(getBaseContext()) + "/" + System.currentTimeMillis() + ".jpg"); FileUtils.createFile(mTmpFile); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getBaseContext(), BuildConfig.APPLICATION_ID + ".provider", mTmpFile)); }else { cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile)); } cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile)); startActivityForResult(cameraIntent, REQUEST_CAMERA); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode){ case REQUEST_CAMERA: if (resultCode == RESULT_OK){ crop(mTmpFile.getAbsolutePath()); }else { Toast.makeText(this, "拍照失敗", Toast.LENGTH_SHORT).show(); } break; case REQUEST_CROP: if (resultCode == RESULT_OK){ rvHead.setImageURI(Uri.fromFile(mCropImageFile)); upHead(mCropImageFile+""); // 把圖片上傳到伺服器 }else { Toast.makeText(this, "截圖失敗", Toast.LENGTH_SHORT).show(); } break; case REQUEST_GALLERY: if (resultCode == RESULT_OK && data != null){ String imagePath = handleImage(data); crop(imagePath); }else { Toast.makeText(this, "開啟相簿失敗", Toast.LENGTH_SHORT).show(); } break; } } private void crop(String imagePath){ //mCropImageFile = FileUtils.createTmpFile(getBaseContext()); mCropImageFile = getmCropImageFile(); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*"); intent.putExtra("crop", true); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 500); intent.putExtra("outputY", 500); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCropImageFile)); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); startActivityForResult(intent, REQUEST_CROP); } //把fileUri轉換成ContentUri public Uri getImageContentUri(File imageFile){ String filePath = imageFile.getAbsolutePath(); Cursor cursor = getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor .getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); return Uri.withAppendedPath(baseUri, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); return getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } //獲取裁剪的圖片儲存地址 private File getmCropImageFile(){ if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),"temp.jpg"); File file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg"); return file; } return null; } private String handleImage(Intent data) { Uri uri = data.getData(); String imagePath = null; if (Build.VERSION.SDK_INT >= 19) { if (DocumentsContract.isDocumentUri(this, uri)) { String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("" + "content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri, null); } } else if ("content".equals(uri.getScheme())) { imagePath = getImagePath(uri, null); } } else { imagePath = getImagePath(uri, null); } return imagePath; } private String getImagePath(Uri uri, String seletion) { String path = null; Cursor cursor = getContentResolver().query(uri, null, seletion, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; }
5.FileUtils:
package com.dahuo.gohome.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import java.io.File;
/**
* Created by $ *** on 2018/9/27 0027.
*/
public class FileUtils {
private static final String TAG = FileUtils.class.getSimpleName();
/**
* 建立根快取目錄
*
* @return
*/
public static String createRootPath(Context context) {
String cacheRootPath = "";
if (isSdCardAvailable()) {
// /sdcard/Android/data/<application package>/cache
cacheRootPath = context.getExternalCacheDir().getPath();
} else {
// /data/data/<application package>/cache
cacheRootPath = context.getCacheDir().getPath();
}
return cacheRootPath;
}
public static boolean isSdCardAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
* 遞迴建立資料夾
*
* @param dirPath
* @return 建立失敗返回""
*/
public static String createDir(String dirPath) {
try {
File file = new File(dirPath);
if (file.getParentFile().exists()) {
Log.i(TAG, "----- 建立資料夾" + file.getAbsolutePath());
file.mkdir();
return file.getAbsolutePath();
} else {
createDir(file.getParentFile().getAbsolutePath());
Log.i(TAG, "----- 建立資料夾" + file.getAbsolutePath());
file.mkdir();
}
} catch (Exception e) {
e.printStackTrace();
}
return dirPath;
}
/**
* 遞迴建立資料夾
*
* @param file
* @return 建立失敗返回""
*/
public static String createFile(File file) {
try {
if (file.getParentFile().exists()) {
Log.i(TAG, "----- 建立檔案" + file.getAbsolutePath());
file.createNewFile();
return file.getAbsolutePath();
} else {
createDir(file.getParentFile().getAbsolutePath());
file.createNewFile();
Log.i(TAG, "----- 建立檔案" + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String getApplicationId(Context appContext) throws IllegalArgumentException {
ApplicationInfo applicationInfo = null;
try {
applicationInfo = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), PackageManager.GET_META_DATA);
if (applicationInfo == null) {
throw new IllegalArgumentException(" get application info = null, has no meta data! ");
}
Log.d(TAG, appContext.getPackageName() + " " + applicationInfo.metaData.getString("APP_ID"));
return applicationInfo.metaData.getString("APP_ID");
} catch (PackageManager.NameNotFoundException e) {
throw new IllegalArgumentException(" get application info error! ", e);
}
}
}