package com.samples.camera.managepreview;

import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CameraPreviewActivity extends Activity 
		implements SurfaceHolder.Callback, View.OnClickListener {

	private Button bStart;
	private Button bStop;
	private SurfaceView surView;
	private SurfaceHolder surHolder;
	
	private Camera camera;
	boolean isCameraPreview = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
      
		bStart = (Button)findViewById(R.id.bStart);
		bStop = (Button)findViewById(R.id.bStop);
      	
		surView = (SurfaceView)findViewById(R.id.surfaceview);
		surHolder = surView.getHolder();
		surHolder.addCallback(this);
		surHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
      
		bStart.setOnClickListener(this);     
		bStop.setOnClickListener(this);   
		
		bStop.setEnabled(false);
	}
	
	@Override
	public void surfaceChanged(
			SurfaceHolder holder, int format, int width, int height) { }

	@Override
	public void surfaceCreated(SurfaceHolder holder) { }

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) { 
		if (isCameraPreview) {
			camera.stopPreview();
			camera.release(); 
			isCameraPreview = false;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bStart:
			try {
				camera = Camera.open();
				camera.setPreviewDisplay(surHolder);
				camera.startPreview();
				isCameraPreview = true;
						
				bStart.setEnabled(!isCameraPreview);
				bStop.setEnabled(isCameraPreview);
			} 
			catch (IOException e) {
			   Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			break;
			
		case R.id.bStop:
			camera.stopPreview();
			camera.release(); 
			isCameraPreview = false;
				
			bStart.setEnabled(!isCameraPreview);
			bStop.setEnabled(isCameraPreview);
			break;
		}		
	}
}