Hello there我是Camera API的newbiew。我正在向我自己學習!我只是想切換我的相機後臺和前臺! 我的設備有前後相機! 我這樣做,如:使用Camera API在Android上切換攝像頭
public class CameraFrag extends Fragment {
//Variables
private Camera mCamera;
private CameraPreview mPreview;
private ToggleButton flipCamera;
////////////////////////////////////
public CameraFrag() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate the layout
View v = inflater.inflate(R.layout.frag, container, false);
flipCamera = (ToggleButton) v.findViewById(R.id.flipper);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(getContext(), mCamera);
FrameLayout preview = (FrameLayout) v.findViewById(R.id.camera_preview);
preview.addView(mPreview);
flipCamera.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
try{
mCamera.stopPreview();
if(isChecked){
mCamera=openFrontFacingCamera();
}
else{
mCamera=openBackFacingCamera();
}
mCamera.startPreview();
}catch(Exception exp){
Log.i("#LOGTAG","EXCEPTION "+exp);
}
}
});
return v;
}
private Camera openBackFacingCamera() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cam = Camera.open(camIdx);
}
}
return cam;
}
private Camera openFrontFacingCamera() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
cam = Camera.open(camIdx);
}
}
return cam;
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
的問題是,它總是拋出異常如:
I /#LOGTAG:EXCEPTION的Java。 lang.RuntimeException:無法連接到相機服務
,如果我用我的代碼爲:
try{
mCamera.stopPreview();
mCamera.release();
if(isChecked){
mCamera=openFrontFacingCamera();
}
else{
mCamera=openBackFacingCamera();
}
mCamera.startPreview();
}catch(Exception exp){
Log.i("#LOGTAG","EXCEPTION "+exp);
}
我的預覽凍結,回來時,我點擊後退按鈕!
我在做什麼錯了?這是在相機之間切換的正確方法嗎?有人可以幫我嗎?
在此先感謝!
什麼版本的Android?你添加了權限嗎? –
API 13 MIn和API 23 MAX –
我在問你正在使用的設備。它是一個設備還是仿真器? –