我是Android的新手程序员我试图通过点击按钮启动Android中的相机预览。我正在尝试直接访问相机硬件,而不是使用默认的相机应用程序。这是我写的代码
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class CameraHandler extends Activity {
private SurfaceView sv = null;
private SurfaceHolder previewHolder = null;
private Button btnStop;
private Button btnStart;
private Camera camera = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameraview);
// Get the surface view from main layout
sv = (SurfaceView) findViewById(R.id.cameraSurface);
// Get the buttons from XML
btnStart = (Button) findViewById(R.id.startButton);
btnStop = (Button) findViewById(R.id.stopButton);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SurfaceHolder.Callback surfaceCallBack = new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.release();
camera = null;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
// TODO Auto-generated catch block
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(CameraHandler.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
// TODO Auto-generated method stub
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
camera.startPreview();
}
};
// Get the surface holder from the surface view
previewHolder = sv.getHolder();
// Now add these call backs
previewHolder.addCallback(surfaceCallBack);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.stopPreview();
}
});
}
}
正如您所看到的,我从SurfaceView中获取表面支架,在单击开始按钮时添加回调。由于某种原因,没有调用SufraceHolder回调。但是,如果我将整个代码直接放在onCreate函数中,它可以正常工作,即在启动活动时启动相机预览。我在这里错过了什么吗?
先谢谢
答案 0 :(得分:3)
单击按钮时已创建SurfaceView
。因此,surfaceCreated()
可能不会被调用。