创建文件夹

   /**
     * 创建一个用于拍照图片输出路径的Uri (FileProvider)
     *
     * @param context
     * @return
     */
 public static Uri getUriForFile(Context context, File file) {
        return FileProvider.getUriForFile(context,  getFileProviderName(context), file);
    }
    /**
     * 获取一个临时的Uri, 文件名随机生成
     *
     * @param context
     * @return
     */
   public static Uri getTempUri(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
//android11 创建文件夹必须使用这种方式
   String timeStampStart= context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        File file = new File(timeStampStart + timeStamp + ".jpg");
 if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return getUriForFile(context, file);
    }

拍照

 

//用于回显的Uri
   private Uri cameraUri;
//在onActivityResult 中判断 回显 cameraUri
private int REQUEST_TAKE_PHOTO=23;

//拍照
private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);   
  if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            // Create the File where the photo should go
                File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {catch (IOException ex) {
                // Error occurred while creating the File
                Log.e("TAG", "dispatchTakePictureIntent: " + ex);
            }
if (photoFile != null) {
                cameraUri = FileProvider.getUriForFile(this,
                        AppUtils.getAppPackageName() + ".fileprovider",
                        photoFile);

  takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
     }
    }

 
/**
     * 将Uri 解析出文件绝对路径
     *
     * @param uri
     * @return
     */
 public static String parseOwnUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }
    String path;
        if (TextUtils.equals(uri.getAuthority(),  getFileProviderName(context))) {
//camera_photos/ 要与<provider><provider/> 对应
            path = new File(uri.getPath().replace("camera_photos/", "")).getAbsolutePath();
        } else {
 path = uri.getPath();
        }
        return path;
    }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐