Android L Camera2 API sample ver1 - startPreview

来源:互联网 发布:淘宝几天可以延迟收货 编辑:程序博客网 时间:2024/05/16 11:19

1. Manifest :

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.camera2te"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="21"        android:targetSdkVersion="21" />    <uses-permission android:name="android.permission.CAMERA" />   <span style="color:#ff0000;"> <uses-feature android:name="android.hardware.camera2.full" /></span>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

2. Layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.camera2te.MainActivity" >        <TextureView        android:id="@+id/texture"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>


3. Java code :

package com.example.camera2te;import java.util.Arrays;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.os.HandlerThread;import android.util.Log;import android.util.Size;import android.view.Surface;import android.view.TextureView;import android.widget.Toast;import android.graphics.SurfaceTexture;import android.hardware.camera2.CameraAccessException;import android.hardware.camera2.CameraCaptureSession;import android.hardware.camera2.CameraCharacteristics;import android.hardware.camera2.CameraDevice;import android.hardware.camera2.CameraManager;import android.hardware.camera2.CameraMetadata;import android.hardware.camera2.CaptureRequest;import android.hardware.camera2.params.StreamConfigurationMap;public class MainActivity extends Activity {private final static String TAG = "Camera2testJ";private Size mPreviewSize;private TextureView mTextureView;private CameraDevice mCameraDevice;private CaptureRequest.Builder mPreviewBuilder;private CameraCaptureSession mPreviewSession;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mTextureView = (TextureView)findViewById(R.id.texture);mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);}@Overrideprotected void onResume() {// TODO Auto-generated method stubsuper.onResume();Log.e(TAG, "onResume");}private void openCamera() {CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);Log.e(TAG, "openCamera E");try {String cameraId = manager.getCameraIdList()[0];CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);mPreviewSize = map.getOutputSizes(SurfaceTexture.class)[0];manager.openCamera(cameraId, mStateCallback, null);} catch (CameraAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}Log.e(TAG, "openCamera X");}private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener(){@Overridepublic void onSurfaceTextureAvailable(SurfaceTexture surface,int width, int height) {// TODO Auto-generated method stubLog.e(TAG, "onSurfaceTextureAvailable, width="+width+",height="+height);openCamera();}@Overridepublic void onSurfaceTextureSizeChanged(SurfaceTexture surface,int width, int height) {// TODO Auto-generated method stubLog.e(TAG, "onSurfaceTextureSizeChanged");}@Overridepublic boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {// TODO Auto-generated method stubreturn false;}@Overridepublic void onSurfaceTextureUpdated(SurfaceTexture surface) {// TODO Auto-generated method stubLog.e(TAG, "onSurfaceTextureUpdated");}};private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {@Overridepublic void onOpened(CameraDevice camera) {// TODO Auto-generated method stubLog.e(TAG, "onOpened");mCameraDevice = camera;startPreview();}@Overridepublic void onDisconnected(CameraDevice camera) {// TODO Auto-generated method stubLog.e(TAG, "onDisconnected");}@Overridepublic void onError(CameraDevice camera, int error) {// TODO Auto-generated method stubLog.e(TAG, "onError");}};@Overrideprotected void onPause() {// TODO Auto-generated method stubLog.e(TAG, "onPause");super.onPause();if (null != mCameraDevice) {            mCameraDevice.close();            mCameraDevice = null;        }}protected void startPreview() {// TODO Auto-generated method stubif(null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {Log.e(TAG, "startPreview fail, return");}SurfaceTexture texture = mTextureView.getSurfaceTexture();if(null == texture) {Log.e(TAG,"texture is null, return");return;}texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());Surface surface = new Surface(texture);try {mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);} catch (CameraAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}mPreviewBuilder.addTarget(surface);try {mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {@Overridepublic void onConfigured(CameraCaptureSession session) {// TODO Auto-generated method stubmPreviewSession = session;updatePreview();}@Overridepublic void onConfigureFailed(CameraCaptureSession session) {// TODO Auto-generated method stubToast.makeText(MainActivity.this, "onConfigureFailed", Toast.LENGTH_LONG).show();}}, null);} catch (CameraAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}protected void updatePreview() {// TODO Auto-generated method stubif(null == mCameraDevice) {Log.e(TAG, "updatePreview error, return");}mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);HandlerThread thread = new HandlerThread("CameraPreview");thread.start();Handler backgroundHandler = new Handler(thread.getLooper());try {mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, backgroundHandler);} catch (CameraAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}



2 1
原创粉丝点击