Android 照相机打开方法
package gongzibai.co.cc;
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.view.View.OnClickListener;
import android.widget.Button;
public class Ex2Activity extends Activity implements SurfaceHolder.Callback {
Camera mCamera;
SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
Button mButton1,mButton2;
boolean isPreview=false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSurfaceView=(SurfaceView)findViewById(R.id.surfaceView1);
mButton1=(Button)findViewById(R.id.button1);
mButton2=(Button)findViewById(R.id.button2);
mSurfaceHolder=mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
initCamera();
}
private void initCamera() {
// TODO Auto-generated method stub
if (!isPreview) {
mCamera=Camera.open();
}
if (mCamera!=null&&!isPreview) {
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
isPreview=true;
}
}
});
mButton2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mCamera!=null&&isPreview) {
mCamera.stopPreview();
mCamera.release();
mCamera=null;
isPreview=false;
}
}
});
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}