MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO=2;
private ImageView picture;
private Button takePhoto;
private Button chooseFromAlbum;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto=findViewById(R.id.take_photo);//获取实例
picture=findViewById(R.id.picture);
chooseFromAlbum=findViewById(R.id.choose_from_album);//获取实例,点击事件
chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//动态申请,危险权限
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
,1);
}else {
openAlbum();//当用户授权了权限申请之后会调用这个方法
}
}
});
takePhoto.setOnClickListener(new View.OnClickListener() {//设点击事件
@Override
public void onClick(View v) {
//创建File 对象,用于存储拍照后的照片
//调用getExternalCacheDir()方法可以得到目录
File outputImage=new File(getExternalCacheDir(),"output_image.jpg");
try {
if (outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT>=24){
//getUriForFile()方法接受3个参数,第一个参数要求传入一个Context对象,
// 第二个参数可以是任意唯一的字符串,第三个参数是刚刚创建的File对象
//FileProvider则是一种特殊的内容提供器
imageUri= FileProvider.getUriForFile
(MainActivity.this,"com.example.cameraalbumtest.fileprovider",outputImage);
}else {
imageUri=Uri.fromFile(outputImage);
}
//启动相机程序
Intent intent =new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);//指定图片的输出地址
startActivityForResult(intent,TAKE_PHOTO);//启动活动
}
});
}
private void openAlbum() {
//构建了一个intent 对象,
Intent intent=new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PHOTO);//打开相册
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1:
if (grantResults.length>0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED){
openAlbum();
}else {
Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case TAKE_PHOTO:
if (requestCode==RESULT_OK){
//将拍摄的照片显示出来
try {
//如果拍照成功调用 BitmapFactory的decodeStream()方法将照片解析成Bitmap对象,然后把它设置成Image View中显示出来
Bitmap bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
case CHOOSE_PHOTO:
if (requestCode ==RESULT_OK){
//判断手机系统版本号
if (Build.VERSION.SDK_INT>=19){
//4.4及以上系统使用这个方法处理图片
handleImageOnKitKat(data);
}else {
//4.4以下系统使用这个方法处理图片
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void handleImageOnKitKat(Intent data) {
String imagePath=null;
Uri uri=data.getData();
if (DocumentsContract.isDocumentUri(this,uri)){
//如果是document 类型的Uri ,则通过document id 处理
String docId=DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())){
String id=docId.split(":")[1];//解析出数据格式的Id
String selection=MediaStore.Images.Media._ID+"="+id;
imagePath =getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
}else if ("com.android.providers.dowmloads.documents".equals(uri.getAuthority())){
Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
imagePath=getImagePath(contentUri,null);
}
}else if ("content".equalsIgnoreCase(uri.getScheme())){
//如果是content 类型的Uri,则使用普通方式处理
imagePath=getImagePath(uri,null);
}else if ("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri ,直接获取图片路径即可
imagePath=uri.getPath();
}
displayImage(imagePath); //根据图片路径显示图片
}
private void handleImageBeforeKitKat(Intent data){
Uri uri=data.getData();
String imagePath=getImagePath(uri,null);
displayImage(imagePath);
}
private String getImagePath(Uri uri, String selection) {
String path=null;
//通过Uri 和selection 来获取真实的图片路径
Cursor cursor =getContentResolver().query(uri,null,selection,null,null);
if (cursor!=null){
if (cursor.moveToFirst()){
path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath) {
if (imagePath !=null){
Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap);
}else {
Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml:
............
.........
res 新建一个file_paths.xml文件:
activity_main.xml: