图片Android知识库安卓实用知识

更完整的 Android 拍照实现教程

2017-03-27  本文已影响396人  极小光
咔嚓

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

作者在学习 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);
}

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>

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
    }
  }

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

日报延伸阅读

欢迎关注

上一篇 下一篇

猜你喜欢

热点阅读