1
我是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();
}
});
}
}
正如你可以看到我從XML的SurfaceView將它添加回調點擊啓動按鈕時,得到表面持有者的代碼。出於某種原因SufraceHolder回調沒有被調用。但是,如果我將這整個代碼直接放在onCreate函數中,它可以正常工作,即在活動啓動時相機預覽開始。我在這裏錯過了什麼嗎?提前
哦..感謝您的快速回答。嘿,有什麼辦法可以實現這一點我的意思是點擊一個按鈕啓動相機預覽? – copyninja 2010-09-05 15:43:10
@Vasudev:在你的OnClickListener中調用camera.startPreview(),但首先完成其餘的設置。 – CommonsWare 2010-09-05 15:58:32
它的工作!非常感謝 :) – copyninja 2010-09-05 17:17:19