android7.0以上打开相机、相册并显示头像(实测好用)

1 调用

private static final int CAMERA_CODE = 200;


 File mFile;
    Uri mImageUri;
    private void openCamera() {
        //创建文件用于保存图片 /storage/emulated/0/Android/data/com.ruhai.yibei/cache/images/1645415716745.jpg
        mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
        if (!mFile.exists()) {
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //适配7.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mImageUri = Uri.fromFile(mFile);
        } else {
            //第二个参数要和清单文件中的配置provider的authorities保持一致
            mImageUri = FileProvider.getUriForFile(PersonInfoActivity.this, "com.ruhai.yibei.provider", mFile);
        }

        //启动相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将拍照图片存入mImageUri
        startActivityForResult(intent, CAMERA_CODE);
    }

2 application便签内部配置provider,android:authorities跟getUriForFile第二个人参数一致


            
        

3 res目录下新建xml文件夹,新建file_paths.xml文件,external-cache-path标签对应文件路径getExternalCacheDir();images对应images/,.表示不用自定义文件夹



    

file_path的配置跟这里相对应
android7.0以上打开相机、相册并显示头像(实测好用)_第1张图片

ps:xml下file_paths.xml跟调用代码对应关系




    
    
    

    
    
    

    
    
    

    
    
    

    
    
    

    
    
    



4打开相册

 private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, ALBUM_CODE);
    }

5显示头像
不从data拿数据,此时data数据是null,直接从上面获取mImageUri跟mFile

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_CODE) {
            if (resultCode == RESULT_OK) {
                try {
                    //Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                    // .openInputStream(mImageUri));
                    //img.setImageBitmap(bitmap);
                    headerImage.setImageURI(mImageUri);
                    //处理照相之后的结果并上传
//                    uploadOk(mFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == ALBUM_CODE) {
            //相册
            if (resultCode == RESULT_OK) {
                Uri imageUri = data.getData();
                //处理uri,7.0以后的fileProvider 把URI 以content provider 方式 对外提供的解析方法
                File file = getFileFromUri(imageUri, this);
                if (file.exists()) {

                    headerImage.setImageURI(imageUri);

//                    headerImage.setImageBitmap(BitmapFactory.decodeFile(file.getName()));
                }
            }
        }
    }

全部代码

package com.ruhai.yibei.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ruhai.yibei.Constant;
import com.ruhai.yibei.R;
import com.ruhai.yibei.bean.PersonInfoBean;

import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

public class PersonInfoActivity extends AppCompatActivity {
    ProgressDialog dialogShibie;
    List fileArrayList;
    private static final int CAMERA_CODE = 200;
    private static final int ALBUM_CODE = 100;


    private TextView backPrivacyImgv;
    private TextView tvNickName;
    private TextView tvEmail;
    private TextView tvPhone;
    private LinearLayout nickNameLl;
    private LinearLayout emailLl;
    private LinearLayout llHeadImage;


    File mFile;
    Uri mImageUri;

    private void openCamera() {
        //创建文件用于保存图片 /storage/emulated/0/Android/data/com.ruhai.yibei/cache/images/1645415716745.jpg
        mFile = new File(getExternalCacheDir(), "images/" + System.currentTimeMillis() + ".jpg");
        if (!mFile.exists()) {
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //适配7.0
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mImageUri = Uri.fromFile(mFile);
        } else {
            //第二个参数要和清单文件中的配置保持一致
            mImageUri = FileProvider.getUriForFile(PersonInfoActivity.this, "com.ruhai.yibei.provider", mFile);
        }
        //启动相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将拍照图片存入mImageUri
        startActivityForResult(intent, CAMERA_CODE);
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, ALBUM_CODE);
    }

    private void getInfo() {
        RequestParams params = new RequestParams(Constant.achieveLoginUser);
        params.addHeader("Authorization", Constant.authorization);
        params.addHeader("language", "zh_CN");

        x.http().get(params, new Callback.CommonCallback() {
            @Override
            public void onSuccess(String result) {

                Log.e("wy", "achieveLoginUser result: " + result);
                PersonInfoBean personInfoBean = JSON.parseObject(result, PersonInfoBean.class);
                Log.e("wy", "getAvatar: " + personInfoBean.getData().getAvatar());
//                String s =  filepath;
//                Bitmap bitmap = BitmapFactory.decodeFile(s);
//                    ivIcon.setImageBitmap(bitmap);
                //headerImage.setImageURI((Uri) personInfoBean.getData().getAvatar());

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("wy", "result: " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 文件上传
     */
    private void uploadOk(File file) {

        dialogShibie.setTitle("上传中");
        dialogShibie.show();

//        Log.e("wy1", "开始上传图片的时间: " + TimeUtil.stampToDate(System.currentTimeMillis() + ""));
        RequestParams params = new RequestParams(Constant.uploadPic);
//        params.setConnectTimeout(5000);
        // 有上传文件时使用multipart表单, 否则上传原始文件流.
        params.setMultipart(true);
        // 上传文件方式 2  /mnt/internal_sd/FtrendCrashLog/th.jpg
        params.addBodyParameter("files", mFile);
//        params.addBodyParameter("file", bitmapUse);
        Log.e("wy", "uploadOk params:   " + params);
        x.http().post(params, new org.xutils.common.Callback.CommonCallback() {
            @Override
            public void onSuccess(String result) {
                dialogShibie.dismiss();
                Toast.makeText(x.app(), "上传图片成功", Toast.LENGTH_SHORT).show();
                Log.e("wy", "result: " + result);

            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    Log.e("wy", "responseCode    " + responseCode);
                    if (responseCode == 404) {
                        dialogShibie.dismiss();
                        Toast.makeText(x.app(), "ip地址错误", Toast.LENGTH_LONG).show();
                    }
                    // ...
                } else { // 其他错误
                    // ...
                }
//                dialogShibie.dismiss();
                Log.e("wy", "请求上传图片地址错误: " + ex.getMessage());
//                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                dialogShibie.dismiss();
                Log.e("wy", "本次请求完全结束 ");

            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_CODE) {
            if (resultCode == RESULT_OK) {
                try {
                    //Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                    // .openInputStream(mImageUri));
                    //img.setImageBitmap(bitmap);
                    headerImage.setImageURI(mImageUri);
                    //处理照相之后的结果并上传
//                    uploadOk(mFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == ALBUM_CODE) {
            //相册
            if (resultCode == RESULT_OK) {
                Uri imageUri = data.getData();
                //处理uri,7.0以后的fileProvider 把URI 以content provider 方式 对外提供的解析方法
                File file = getFileFromUri(imageUri, this);
                if (file.exists()) {

                    headerImage.setImageURI(imageUri);

//                    headerImage.setImageBitmap(BitmapFactory.decodeFile(file.getName()));
                }
            }
        }
    }

    private void updateFile(File mFile) {

        dialogShibie.setTitle("上传中");
        dialogShibie.show();

        RequestParams params = new RequestParams(Constant.uploadPic);
        params.addHeader("Authorization", Constant.authorization);
//        params.setConnectTimeout(5000);
        // 有上传文件时使用multipart表单, 否则上传原始文件流.
//        params.setMultipart(true);
        // 上传文件方式 2  /mnt/internal_sd/FtrendCrashLog/th.jpg
        params.addBodyParameter("files", mFile);
//        params.addBodyParameter("file", bitmapUse);
        Log.e("wy", "params:   " + params);
        x.http().post(params, new org.xutils.common.Callback.CommonCallback() {
            @Override
            public void onSuccess(String result) {
                dialogShibie.dismiss();
                Toast.makeText(x.app(), "上传图片成功", Toast.LENGTH_SHORT).show();
                Log.e("wy", "result: " + result);

            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    Log.e("wy", "responseCode    " + responseCode);
                    if (responseCode == 404) {
                        dialogShibie.dismiss();
                        Toast.makeText(x.app(), "ip地址错误", Toast.LENGTH_LONG).show();
                    }
                    // ...
                } else { // 其他错误
                    // ...
                }
//                dialogShibie.dismiss();
                Log.e("wy", "uploadPic接口报错原因: " + ex.getMessage());
//                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                dialogShibie.dismiss();
                Log.e("wy", "本次请求完全结束 ");

            }
        });

    }

    public File getFileFromUri(Uri uri, Context context) {
        if (uri == null) {
            return null;
        }
        Log.e("wy", "getScheme: " + uri.getScheme());
        switch (uri.getScheme()) {

            case "content":
                return getFileFromContentUri(uri, context);
            case "file":
                return new File(uri.getPath());
            default:
                return null;
        }
    }

    /**
     * 通过内容解析中查询uri中的文件路径
     */
    private File getFileFromContentUri(Uri contentUri, Context context) {
        if (contentUri == null) {
            return null;
        }
        File file = null;
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(contentUri, filePathColumn, null,
                null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            Log.e("wy", "filePath: " + filePath);
            cursor.close();

            if (!TextUtils.isEmpty(filePath)) {
                file = new File(filePath);
            }
        }
        return file;
    }

    private ImageView headerImage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        headerImage = (ImageView) findViewById(R.id.header_image);
        dialogShibie = new ProgressDialog(this);
        llHeadImage = (LinearLayout) findViewById(R.id.ll_head_image);
        llHeadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                new Dialog()
//                openCamera();
                openAlbum();
            }
        });

        backPrivacyImgv = (TextView) findViewById(R.id.back_privacy_imgv);
        backPrivacyImgv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tvNickName = (TextView) findViewById(R.id.tv_nick_name);
        tvEmail = (TextView) findViewById(R.id.tv_email);
        tvPhone = (TextView) findViewById(R.id.tv_phone);


        nickNameLl = (LinearLayout) findViewById(R.id.nick_name_ll);
        nickNameLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonInfoActivity.this, ModifyPersonInfoActivity.class);
                intent.putExtra("infoName", "nickName");
                startActivity(intent);
            }
        });
        emailLl = (LinearLayout) findViewById(R.id.email_ll);
        emailLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonInfoActivity.this, ModifyPersonInfoActivity.class);
                intent.putExtra("infoName", "email");
                startActivity(intent);
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        getInfo();
        tvNickName.setText(Constant.nickName);
        tvEmail.setText(Constant.email);
        tvPhone.setText(Constant.phone);
    }
}

你可能感兴趣的:(打开相机,打开相册)