首页 > 代码库 > Android L Camera2 API sample ver1 - startPreview

Android L Camera2 API sample ver1 - startPreview

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;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mTextureView = (TextureView)findViewById(R.id.texture);
		mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.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 block
			e.printStackTrace();
		}
		Log.e(TAG, "openCamera X");
	}
	
	private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener(){

		@Override
		public void onSurfaceTextureAvailable(SurfaceTexture surface,
				int width, int height) {
			// TODO Auto-generated method stub
			Log.e(TAG, "onSurfaceTextureAvailable, width="+width+",height="+height);
			openCamera();
		}

		@Override
		public void onSurfaceTextureSizeChanged(SurfaceTexture surface,
				int width, int height) {
			// TODO Auto-generated method stub
			Log.e(TAG, "onSurfaceTextureSizeChanged");
		}

		@Override
		public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void onSurfaceTextureUpdated(SurfaceTexture surface) {
			// TODO Auto-generated method stub
			Log.e(TAG, "onSurfaceTextureUpdated");
		}
		
	};
	
	private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

		@Override
		public void onOpened(CameraDevice camera) {
			// TODO Auto-generated method stub
			Log.e(TAG, "onOpened");
			mCameraDevice = camera;
			startPreview();
		}

		@Override
		public void onDisconnected(CameraDevice camera) {
			// TODO Auto-generated method stub
			Log.e(TAG, "onDisconnected");
		}

		@Override
		public void one rror(CameraDevice camera, int error) {
			// TODO Auto-generated method stub
			Log.e(TAG, "onError");
		}
		
	};

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.e(TAG, "onPause");		
		super.onPause();
		if (null != mCameraDevice) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
	}

	protected void startPreview() {
		// TODO Auto-generated method stub
		if(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 block
			e.printStackTrace();
		}
		mPreviewBuilder.addTarget(surface);
		
		try {
			mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
				
				@Override
				public void onConfigured(CameraCaptureSession session) {
					// TODO Auto-generated method stub
					mPreviewSession = session;
					updatePreview();
				}
				
				@Override
				public void onConfigureFailed(CameraCaptureSession session) {
					// TODO Auto-generated method stub
					Toast.makeText(MainActivity.this, "onConfigureFailed", Toast.LENGTH_LONG).show();
				}
			}, null);
		} catch (CameraAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void updatePreview() {
		// TODO Auto-generated method stub
		if(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 block
			e.printStackTrace();
		}
	}
}



Android L Camera2 API sample ver1 - startPreview