Android11调用相机保存图片的方法

原文链接:Android11调用相机保存并显示图片到imageview_Cingke是真的的博客-CSDN博客

 android11版本因为加强了创建文件的限制,所以用以前保存图片的方法就行不通了。

1、在获取相关权限后,调用相机

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//确保有相机来处理Intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
    File photoFile = saveFileName1();
    tempFile1 = photoFile;
    if (photoFile != null) {
        Uri photoURI = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", photoFile);
        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(takePictureIntent, 1);
    }
}

2、配置FileProvider,用于app之间的文件共享

//在application标签里

    
    

   之后配置对应路径的xml文件



    

 

3、保存位置

private String currentPath;//配置全局变量

private File saveFileName1() {
    
    File newFolder = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date(System.currentTimeMillis());
    String name = format.format(date) + ".jpg";
    File ji = null;
    try {
        ji = new File(newFolder + "/" + name);
        ji.createNewFile();
        currentPath = ji.getAbsolutePath();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ji;
}

 

4、处理返回结果 

@Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       // TODO Auto-generated method stub
       super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == 0) {
           FileOutputStream o=null;
           Bitmap bitmap=BitmapFactory.decodeFile(currentPath);
           //显示
           image.setImageBitmap(bitmap);
          //图片在文件管理器打不开,需要移出应用私有目录才可查看
       }
   }
 

你可能感兴趣的:(android,java,apache)