本文章只是讲解在Android中调用摄像头, 并无拍照功能。
权限申请:
<uses-permission android:name="android.permission.CAMERA" />
首先, 我们需要先在XML里添加一个SurfaceView控件来显示摄像头拍摄到的画面。
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SurfaceView
android:id="@+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</SurfaceView>
</LinearLayout>
然后, 在JAVA中我们需要实现SurfaceHolder.Callback这个接口, 它有三个方法
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
InitCamera();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
surfaceChanged: 当摄像头屏幕改变时
surfaceCreated: 当摄像头创建完毕时(我们可以在这里对摄像头进行初始化)
surfaceDestroyed:摄像头关闭时
下面是源码:
public class Page extends Activity implements SurfaceHolder.Callback
{
private Camera mCamera;
private SurfaceHolder mSurfaceHolder; //SurfaceView的控制类
private SurfaceView mSurfaceView;
private boolean isPreview = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.ar_page);
mSurfaceView = (SurfaceView)findViewById(R.id.surface);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this); //设置回调
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
//初始化摄像头
InitCamera();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
private void InitCamera()
{
if(isPreview)
return;
mCamera = Camera.open();
if(mCamera != null)
{
try
{
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.setDisplayOrientation(90); //注意: 该方法实现摄像头90度旋转(摄像头默认是横的) 需2.2及以上版本
mCamera.startPreview();
} catch (Exception e)
{
// TODO: handle exception
}
isPreview = true;
}
}
}
要注意,在关闭应用时必须释放摄像头, 否则下次开启时, 由于摄像头被占用, 就会导致程序出错。 其它使用了摄像头的软件也一样。
@Override
protected void onPause()
{
super.onPause();
if (mCamera != null)
{
mCamera.release();
mCamera = null;
}
}