更完整的 Android 拍照实现教程

《更完整的 Android 拍照实现教程》 咔嚓

简评:官方文档也可能会有不足,多踩坑,多分享。

作者在学习 Google 官方的 Android 拍照教程 – Take Photos Simply 时,遇到了一些问题,感觉官方教程只写了 90%。为此,作者写了这篇文章,把完整的流程和一些要注意的地方都写了下来,让你不用再去查 StackOverflow 或者 Github Gist。

1.创建图片文件

File imageFile; // use this to keep a reference to the file you create so that we can access it from onActivityResult()

private void createImageFile() throws IOException {
    String imageFileName = "image" + System.currentTimeMillis() + "_"; // give it a unique filename
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    // use this if you want android to automatically save it into the device's image gallery:
    // File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
    
    imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
}
  • 确保每个文件名都独一无二,所以这里用到了 System.currentTimeMillis()。
  • 注意代码中注释掉的那两行,用它们会将拍的照片存放在手机相册中,在 Android 6.0 (API level 23) 以上,你需要动态申请权限,可以考虑用 Permiso 库来简化你的工作。

2.声明权限

如果打算将照片存放在应用的私有目录中,对于 Android 4.3 及以下的系统需要 WRITE_EXTERNAL_STORAGE 权限。

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                    android:maxSdkVersion="22" />
    
    <!--- If you want to save to the public image directory (the image gallery), you need to do this:
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    --->
    ...
</manifest>
  • 要求了 WRITE_EXTERNAL_STORAGE 权限的同时,也自然有了 READ_EXTERNAL_STORAGE 权限。
  • 如果是想把照片保存在手机相册目录下,所有版本的系统都需要 WRITE_EXTERNAL_STORAGE 权限。
  • 官方文档中的 maxSdkVersion 为 18,可能会导致这个问题:stackoverflow

3.配置 FileProvider

在 AndroidManifest.xml 中增加 FileProvider:

<application>
   ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="{your.app.package}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths"/>
    </provider>
    ...
</application>
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <external-path name="external_files" path="."/>
</paths>

4.创建和开始 Intent

当创建 Intent 时,判断当前设备是否有摄像头并且能接受这个 Intent。此外,需要额外添加 flag 来授权相机能写入我们提供的文件。

public void startCameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
      try {
        imageFile = createImageFile();
      } catch (IOException e) {
        // file wasn't created
      }

      if (imageFile != null) {
        Uri imageUri = FileProvider.getUriForFile(
            ExampleActivity.this,
            BuildConfig.APPLICATION_ID + ".fileprovider", 
            imageFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        // This is important. Without it, you may get Security Exceptions.
        // Google fails to mention this in their docs...
        // Taken from: https://github.com/commonsguy/cw-omnibus/blob/master/Camera/FileProvider/app/src/main/java/com/commonsware/android/camcon/MainActivity.java
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
          ClipData clip = ClipData.newUri(getContentResolver(), "A photo", imageUri);

          intent.setClipData(clip);
          intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        else {
          List<ResolveInfo> resInfoList =
              getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

          for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
          }
        }
      }

      startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }
    else {
      // device doesn't have camera
    }
  }
  • 注意其中的 BuildConfig.APPLICATION_ID + “.fileprovider” 是和 AndroidManifest.xml 中 provider 的 android:authorities 值一致的。

5.获取结果

@Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {  // note that data will be null  
    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == REQUEST_CODE_CAMERA) {
        // imageFile will have the photo in it so do whatever you want with it
      }
    }
 }

原文:The Missing Documentation: Camera Intents

日报延伸阅读

欢迎关注

  • 知乎专栏「极光日报」,每天为 Makers 导读三篇优质英文文章。
  • 网易云电台「极光日报**」,上下班路上为你读报。
点赞