适配android各版本的拍照,并预览的功能

原理:

  1. 以StartActivity方式启动《相机App》的Activity,同时需要把一个临时文件以Extra的方式传递给它
  2. 用户在《相机》中拍照,并点选“ok”时,结束该Activity,返回到onActivityResult()的回调中
  3. 此时,临时文件已经被写入照片
  4. 在回调中,读取临时文件,并放置到ImageView中,供预览!

工作步骤:

1. 我们的Activity(其中一个按钮,点击去拍照,一个ImageView,供拍照后预览)

package cn.john.app1;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.FileNotFoundException;

public class PhotoActivity extends AppCompatActivity {
    private String TAG=PhotoActivity.class.getName();
    private Uri imgUri; //记录拍照后的照片文件的地址(临时文件)
    private ImageView imgView;//用于查看照片的view
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        imgView=findViewById(R.id.imgView);
    }

    /**
     * 按钮事件处理
     */
    public void camera(View view) throws Exception{

        //删除并创建临时文件,用于保存拍照后的照片
        //android 6以后,写Sdcard是危险权限,需要运行时申请,但此处使用的是"关联目录",无需!
        File outImg=new File(getExternalCacheDir(),"temp.jpg");
        if(outImg.exists()) outImg.delete();
        outImg.createNewFile();

        //复杂的Uri创建方式
        if(Build.VERSION.SDK_INT>=24)
            //这是Android 7后,更加安全的获取文件uri的方式(需要配合Provider,在Manifest.xml中加以配置)
            imgUri=FileProvider.getUriForFile(this,"cn.john.app1.fileprovider",outImg);
        else
            imgUri=Uri.fromFile(outImg);

        //利用actionName和Extra,启动《相机Activity》
        Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
        startActivityForResult(intent,1);
        //到此,启动了相机,等待用户拍照
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        switch (requestCode){
            case 1:
                //此时,相机拍照完毕
                if(resultCode==RESULT_OK){
                    try {
                        //利用ContentResolver,查询临时文件,并使用BitMapFactory,从输入流中创建BitMap
                        //同样需要配合Provider,在Manifest.xml中加以配置
                        Bitmap map=BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
                        imgView.setImageBitmap(map);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
        }
    }
}

2. AndroidManifest.xml中的配置片段

      <activity android:name=".PhotoActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--android:authorities与代码中的第二个参数配合,imgUri=FileProvider.getUriForFile(PhotoActivity.this,"cn.john.app1.fileprovider",outImg);-->
        <provider
            android:authorities="cn.john.app1.fileprovider"
            android:name="androidx.core.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <!--此处配置,对外暴露的路径信息-->
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

3. 暴露给FileProvider的目录配置(文件名:res/xml/file_paths.xml)

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"
        path="" />
</paths>
  • 注意:
    (1) <external-path/>:的表示如下表
<root-path/> 代表设备的根目录new File("/");
<files-path/> 代表context.getFilesDir()
<cache-path/> 代表context.getCacheDir()
<external-path/> 代表Environment.getExternalStorageDirectory()
<external-files-path>代表context.getExternalFilesDirs()
<external-cache-path>代表getExternalCacheDirs()

(2)name="my_images":是自己任意指定的标识
(3)path="":相对路径(不设置相当于起点路径)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。