其他分享
首页 > 其他分享> > Android Camera1最简单的预览框显示

Android Camera1最简单的预览框显示

作者:互联网

Android Camera1最简单的预览框显示

Android要预览Camer界面其实非常简单,只需要几句话就行。

1、首先要再AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.CAMERA"/>

2、创建一个xml包含控件TextureView

比如activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="0.8dp"
        android:text="stop preview"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"/>
    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="0.8dp"
        android:text="start preview"
        android:layout_alignParentBottom="true"
        android:layout_toStartOf="@id/btnStop"/>

</RelativeLayout>

3、在Activity创建使用Camera

(1)使用Camera.open(0)获取Camera对象
(2)Camera进行参数设置,最后执行camera.startPreview
(3)关闭预览框的时候释放一下对象就行

比如下面的MainActivity.java代码:

package com.lwz.camera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Camera2Test";
    private TextureView mTextureView; //预览框对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate!");
        setContentView(R.layout.activity_main);
        intiView();
        initEvent();
    }

    private void intiView() {
        mTextureView = (TextureView) findViewById(R.id.textureView);
    }

    private void initEvent() {
        //预览按钮点击监听
        findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i(TAG, "btnStart!");
                startPreview();
            }
        });
        //停止预览按钮点击监听
        findViewById(R.id.btnStop).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i(TAG, "btnStop!");
                stopPreview();
            }
        });

        //预览框状态监听
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                Log.i(TAG, "onSurfaceTextureAvailable width = " + width + ",height = " + height);
                //当SurefaceTexture可用的时候,可以设置相机参数并打开相机
                handleRequestCamera(surface);
                //handleRequestCamera(mTextureView.getSurfaceTexture()); //如果和mTextureView是同一个类内,效果和上面是一样的
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
                Log.i(TAG, "onSurfaceTextureSizeChanged width = " + width + ",height = " + height);
            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                Log.i(TAG, "onSurfaceTextureDestroyed!");
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
                //正常预览的时候,会一直打印
                //Log.i(TAG, "onSurfaceTextureUpdated!");
            }
        });
    }


    Camera mCameram; //可以用来对打开的摄像头进行关闭,释放
    int mCameraId = 0;

    private void handleRequestCamera(SurfaceTexture texture) {
        Log.i(TAG, "handleRequestCamera");
        //简单的判断权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.CAMERA"}, 100);
            Log.e(TAG, "openCamera no Permission!");
            Toast.makeText(this, "无摄像头权限", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            //0/1/2
            mCameram = Camera.open(mCameraId);//手机上可以用来切换前后摄像头,不同的设备要看底层支持情况
            Log.i(TAG, "handleRequestCamera mCameraId = " + mCameraId);
            Camera.Parameters parameters = mCameram.getParameters();
            parameters.setPreviewSize(720, 1280);
//            parameters.setPreviewSize(1280, 720);//不同的设备屏幕尺寸不同,有的设备设置错误的尺寸会崩溃
            mCameram.setParameters(parameters);
            mCameram.setPreviewTexture(texture);
            mCameram.startPreview();
        } catch (Exception error) {
            Log.e(TAG, "handleRequestCamera error = " + error.getMessage());
        }
    }

    /**
     * 开始预览
     */
    private void startPreview() {
        Log.i(TAG, "startPreview");
        SurfaceTexture mSurfaceTexture = mTextureView.getSurfaceTexture();
        handleRequestCamera(mSurfaceTexture);
    }

    /**
     * 停止预览
     * 根据情况选择是否释放,
     * 可以stopPreview,停止预览界面,后面用startPreview可以恢复预览界面
     */
    private void stopPreview() {
        if (mCameram != null) {
            mCameram.stopPreview();
            mCameram.release();
            mCameram = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPreview();//界面退出要释放对象
    }
}

需要注意的是,调用Camera.open之前,要确保预览框已经准备好了,
即onSurfaceTextureAvailable方法已经回调,正常界面显示的时候,都是没有问题的,
但是如果在代码中,View或者Activity创建的时候调用Camera.open,这时候是无法预览界面的,
如果需要代码多处,调用Camera.open,正常做法可以设置一个全局变量,判断SurfaceTexture是否可用。

共勉: 祝大家母亲节快乐。

标签:Log,预览,Camera1,void,TAG,import,Android,android
来源: https://blog.csdn.net/wenzhi20102321/article/details/116562879