调用相机照相

2019-03-17  本文已影响0人  思倦ai

先献上官方连接 https://developer.android.com/training/camera/photobasics
不得不说官方文档还是值得读的 每次读都会有新的收获

最近打算写博客 是因为觉得纸上得来终觉浅 绝知此事要躬行 写下来 理解的更深入 更重要的原因是 交了女朋友 想让自己更成熟稳重点 做事不能犀利弧度 总要做出个样子出来 哈哈😄 可我是一个没有什么毅力的人 不要太相信我 我也不知道能坚持多久


首先构造intent

static final int REQUEST_IMAGE_CAPTURE = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

增加一层if判断 以防NotFoundException
如果仅仅只需要缩略图

  if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        imageView.setImageBitmap(imageBitmap);
    }

这样就可以满足
但是如果需要获取完整的图片信息 需要传递给intent一个uri的地址 相当于共享文件 android7.0以后不允许对外抛出file类型的uri 需要做一层转换 因为调用系统照相机 是两个app的交互过程

 Uri photoURI = FileProvider.getUriForFile(this "com.example.android.fileprovider",photoFile);
 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
 startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

通过fileprovider 做file ->content 协议的转换
这样当成功返回的时候 上面uri的地址存的就是图片信息
关于fileprovider的使用

  1. Defining a FileProvider
  2. Specifying Available Files
  3. Retrieving the Content URI for a File
  4. Granting Temporary Permissions to a URI
  5. Serving a Content URI to Another App


    参考地址
    https://developer.android.com/training/camera/photobasics
    https://developer.android.com/reference/android/support/v4/content/FileProvider.html
    https://www.jianshu.com/p/55eae30d133c
    https://blog.csdn.net/lmj623565791/article/details/72859156
上一篇下一篇

猜你喜欢

热点阅读