实现Android拍照后获取图片的URI

1. 整体流程

首先让我们来看一下整个流程的步骤:

sequenceDiagram
    participant 小白
    participant 经验丰富的开发者

    小白->>经验丰富的开发者: 请求帮助
    经验丰富的开发者->>小白: 解答问题

2. 每一步的实现

步骤一:添加权限

在AndroidManifest.xml文件中添加相机权限:

```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

### 步骤二:创建FileProvider

在AndroidManifest.xml文件中添加FileProvider:

```markdown
```xml
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.example.yourapp.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

### 步骤三:创建file_paths.xml

在res/xml/目录下创建file_paths.xml文件:

```markdown
```xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="
    <external-path name="my_images" path="Android/data/com.example.yourapp/files/Pictures" />
</paths>

### 步骤四:启动相机并拍照

在Activity中启动相机并拍照,将照片保存到指定路径:

```java
```java
private static final int REQUEST_IMAGE_CAPTURE = 1;
private String currentPhotoPath;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.yourapp.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

### 步骤五:获取照片的URI

在onActivityResult方法中获取拍照后的照片URI:

```java
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Uri photoUri = Uri.parse(currentPhotoPath);
        // 使用photoUri进行后续操作
    }
}

## 结尾

通过以上步骤,你可以成功实现在Android应用中拍照后获取照片的URI。希望这篇文章对你有所帮助,如果有任何疑问欢迎继续向我提问。加油,小白!你一定可以做得很好!