做应用可能有时候需要调用本地的摄像头,所以这里就记录意下如何调用。
摄像头预览需要在布局文件添加surfaceview, 这里需要注意,其实用FrameLayout也可以,大家可以参考
http://www.cnblogs.com/over140/archive/2011/11/16/2251344.html
1、布局
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/surfaceview"/>
只要在布局文件添加这个即可。
2、摄像头预览
public class MainActivity extends Activity implements SurfaceHolder.Callback
继承Activity,实现SurfaceHolder.Callback,MainActivity里需要我们复写以下几个方法:
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
System.out.println("surfacechanged");
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("surfacecreated");
//获取camera对象
camera = Camera.open();
try {
//设置预览监听
camera.setPreviewDisplay(holder);
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation
!= Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
//启动摄像头预览
camera.startPreview();
System.out.println("camera.startpreview");
} catch (IOException e) {
e.printStackTrace();
camera.release();
System.out.println("camera.release");
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
System.out.println("surfaceDestroyed");
if (camera != null) {
camera.stopPreview();
camera.release();
}
}
当然还有onCreate方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
surfaceview = (SurfaceView)findViewById(R.id.surfaceview);
surfaceholder = surfaceview.getHolder();
surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceholder.addCallback(SafeActivity.this);
}
,
当然有些变量还需要定义,
private static Context context = null;
private SurfaceView surfaceview;
private SurfaceHolder surfaceholder;
private Camera camera = null;