对网上关于Android7.0,8.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);
}
}
}