安卓开发之调用摄像头

作者:郭霖

最近一直在学习安卓开发,却从来也没有做过相应的记录,下面我们要

介绍的时候运用手机多媒体资源之手机摄像头的调用


首先我们创建一个CameraAlbumTest项目,然后修改activity_main.xml中的代码 

我们就简单加入一个按钮,一个图像控件,然后使用线性布局垂直分布,图像居中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo"/>

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>

然后我们在主活动MainActivity页面添加相应的逻辑代码

package com.gougoucompany.clarence.cameraalbumtest;

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.Button;
import android.widget.ImageView;

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

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;

    private ImageView picture;

    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = (Button) findViewById(R.id.take_photo);
        picture = (ImageView) findViewById(R.id.picture);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建File对象,用于存储拍照后的图片
                //getExternalCacheDir()方法将图片存放在应用关联缓存目录下,也就是/sdcard/Android/data/应用的包名/cache中
                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                    try {
                    //如果文件存在则删除,从新创建一个新的文件
                    if(outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                /*如果运行设备的系统版本低于Android7.0,就调用Uri的fromFile()方法
                * 将File对象转换成Uri对象,这个Uri对象标识着output_image.jpg这张
                * 图片的本地真实路径;否则调用FileProvider的getUriForFile()方法将File
                * 对象转换成一个封装过的Uri对象。
                * 三个参数: Context对象 任意唯一的字符串 File对象
                * 因为Android7.0之后就认为直接使用本地真实路径Uri是不安全的,会抛出FileUriExposed
                * Exception异常。而FileProvider使用一种特殊的内容提供器,它使用了和内容
                * 提供其类似的机制来对数据进行保护,可以选择性地将封装过的Uri共享给外部,从而提高了
                * 应用的安全性*/
                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(MainActivity.this,
                            "com.gougoucompany.clarence.cameraalbumtest.fileprovider", outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                //启动相机程序
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                //指定图片的输出地址
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                //使用startActivityForResult()方法启动活动,因此拍完照片后会有结果返回到onActivityResult()方法中
                //如果发现拍照成功,就可以调用BitmapFactory的decodeStream()方法将ouput_iamge.jpg这张照片解析成Bitmap
                //对象,然后把它设置到ImageView中显示出来
                startActivityForResult(intent, TAKE_PHOTO);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case TAKE_PHOTO:
                if(resultCode == RESULT_OK) {
                    try {
                        //将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch(FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
}

我们使用Intent来启动相机程序,并使用input.putExtral(键,值)方法在意图中绑定一个数据 第二个参数是要传递的值

然后我们使用startActivityForResult()方法启动活动,并在方法中传入一个状态码,并在onActivityResult()方法中完成

将照片显示出来的逻辑。


startActivityForResult()

这里我们介绍一下startActivityForResult()方法

开启Activity的方法有两种: 一种是startActivity(Intent intent) 另一种就是startActivityForResult(Intent intent, int requestCode)

第一种:

Intent intent = new Intent(当前activity.this, 要启动的activity.class);

startActivity(intent);

要销毁一个活动就使用finish()或者Back键就可以了(实际上是返回栈中最顶层活动的出栈操作,大家有兴趣可以看一下返回栈这个东西)

第二种:

使用场景:如果想在当前Activity中,得到新打开的Activity关闭后返回的数据

使用系统提供的(Context)startActivityForResult(Intent intent, int requestCode)方法打开新的Activity

新的Activity中使用setResult(int resultCode, Intent intent)方法,向前面Activity传回数据,为了得到传回的

数据,必须在前面的Activity中重写onActivityResult(int requestCode, int resultCode, Intent data)方法

requestCode请求码,即调用startActivityForResult()传递过去的请求码

resultCode结果码,结果码用于表示返回数据来自哪个新的Activity


刚才使用到了内容提供器,我们要在AndroidManifest.xml中注册,并且指定内容提供其的名字(唯一),authorities(FileProvider.getUriForFile()方法中的第二个参数).还在<provider>标签的内部使用<meta-data>来指定Uri

的共享数据,并引用一个@xml/file_paths资源。并且在Android4.4之前,访问SD卡的应用关联目录也是要声明权限的,从4.4系统开始不再需要权限声明,为了兼容老版本系统,我们声明访问SD卡的权限

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gougoucompany.clarence.cameraalbumtest">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.gougoucompany.clarence.cameraalbumtest.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    </application>

</manifest>

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

path设置空值表示将整个SD卡进行共享


运行之后你就可以在真机上玩耍了

猜你喜欢

转载自blog.csdn.net/qq_32252957/article/details/79844091