有时无法连接到相机服务

时间:2016-01-19 05:29:47

标签: android-fragments android-camera

在调用班级摄像机的前2次调用我的摄像头功能时,我会打开但是如果我正在调用班级第三次应用程序崩溃。

  private int findFrontFacingCamera() {
    int cameraId = 0;
    // Search for the front facing camera
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            cameraId = i;
            cameraFront = true;
            break;
        }
    }
    return cameraId;
}

private int findBackFacingCamera() {
    int cameraId = -1;
    //Search for the back facing camera
    //get the number of cameras
    int numberOfCameras = Camera.getNumberOfCameras();
    //for every camera check
    for (int i = 0; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
            cameraId = i;
            cameraFront = false;
            break;
        }
    }
    return cameraId;
}

public void onResume() {
    super.onResume();
    if (!hasCamera(myContext)) {
        Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
        toast.show();
        finish();
    }
    if (mCamera == null) {
        //if the front facing camera does not exist
        if (findFrontFacingCamera() < 0) {
            Toast.makeText(getActivity().getApplicationContext(), "No front facing camera found.", Toast.LENGTH_LONG).show();
            switchCamera.setVisibility(View.GONE);
        }
        mCamera = Camera.open(findFrontFacingCamera());
        mPicture = getPictureCallback();

        mPreview.refreshCamera(mCamera);
    }
}

logcat的

01-19 10:56:15.164  11477-11477/com.example.siva.prep E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.siva.prep, PID: 11477
    java.lang.RuntimeException: Fail to connect to camera service
            at android.hardware.Camera.native_setup(Native Method)
            at android.hardware.Camera.<init>(Camera.java:393)
            at android.hardware.Camera.open(Camera.java:347)
            at com.example.siva.prep.Selfie.onResume(Selfie.java:146)

它在&#34; onResume()&#34;中的以下行显示错误方法:

mCamera = Camera.open(findFrontFacingCamera());

以下是我正在使用的完整代码:

public class Selfie extends Fragment implements OnClickListener {
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private Button capture, switchCamera;
private Context myContext;
private LinearLayout cameraPreview;
private boolean cameraFront = false;
Bitmap bmp;
ImageView iv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_selfie, container, false);
 //   getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    iv=(ImageView) view.findViewById(R.id.image);
    myContext = getActivity().getApplicationContext();

    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    cameraPreview = (LinearLayout) view.findViewById(R.id.camera_preview);
    mPreview = new CameraPreview(myContext, mCamera);
    cameraPreview.addView(mPreview);

    ImageView capture = (ImageView) view.findViewById(R.id.button_capture);
    capture.setOnClickListener(captrureListener);

    ImageView switchCamera = (ImageView) view.findViewById(R.id.button_ChangeCamera);
    switchCamera.setOnClickListener(switchCameraListener);

    ImageView button1 = (ImageView) view.findViewById(R.id.back);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            FreeFragment fragment2 = new FreeFragment();
            FragmentManager fragmentManager = getFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, fragment2);
            fragmentTransaction.commit();
        }
    });
    getSupportActionBar().hide();
    return view;
}



private ActionBar getSupportActionBar() {
    return ((AppCompatActivity) getActivity()).getSupportActionBar();
}

@Override
public void onClick(View v) {
}

private int findFrontFacingCamera() {
    int cameraId = 0;
    // Search for the front facing camera
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            cameraId = i;
            cameraFront = true;
            break;
        }
    }
    return cameraId;
}

private int findBackFacingCamera() {
    int cameraId = -1;
    //Search for the back facing camera
    //get the number of cameras
    int numberOfCameras = Camera.getNumberOfCameras();
    //for every camera check
    for (int i = 0; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
            cameraId = i;
            cameraFront = false;
            break;
        }
    }
    return cameraId;
}

public void onResume() {
    super.onResume();
    if (!hasCamera(myContext)) {
        Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
        toast.show();
        finish();
    }
    if (mCamera == null) {
        //if the front facing camera does not exist
        if (findFrontFacingCamera() < 0) {
            Toast.makeText(getActivity().getApplicationContext(), "No front facing camera found.", Toast.LENGTH_LONG).show();
            switchCamera.setVisibility(View.GONE);
        }
        mCamera = Camera.open(findFrontFacingCamera());
        mPicture = getPictureCallback();

        mPreview.refreshCamera(mCamera);
    }
}

private void finish() {
}

OnClickListener switchCameraListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        //get the number of cameras
        int camerasNumber = Camera.getNumberOfCameras();
        if (camerasNumber >= 1) {
            //release the old camera instance
            //switch camera, from the front and the back and vice versa

            releaseCamera();
            chooseCamera();
        } else {
            Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
            toast.show();
        }
    }
};

public void chooseCamera() {
    //  if the camera preview is the front
    if (cameraFront) {
        int cameraId = findBackFacingCamera();
        if (cameraId <= 0) {
            //open the backFacingCamera
            //set a picture callback
            //refresh the preview

            mCamera = Camera.open(cameraId);
            mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
        }
    } else
    {
        int cameraId = findFrontFacingCamera();
        if (cameraId >= 0) {
            //open the backFacingCamera
            //set a picture callback
            //refresh the preview

            mCamera = Camera.open(cameraId);
            mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
        }
    }
}

@Override
public void onPause() {
    super.onPause();
    //when on Pause, release camera in order to be used from other applications
    releaseCamera();
}

private boolean hasCamera(Context context) {
    //check if the device has camera
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        return true;
    } else {
        return false;
    }
}

private PictureCallback getPictureCallback() {
    PictureCallback picture = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            //make a new picture file
            File pictureFile = getOutputMediaFile();



            if (pictureFile == null) {
                return;
            }
            try {
                //write the file
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
                Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
                iv.setImageURI(Uri.fromFile(pictureFile));

                //Intent intent = new Intent(AndroidCameraExample.this,Fina.class);
                String stringUri;
                stringUri = pictureFile.toString();
                //intent.putExtra("imagePath", stringUri);
                //startActivity(intent);

                FreeFragment ldf = new FreeFragment ();
                Bundle args = new Bundle();
                args.putString("Image", stringUri);
                ldf.setArguments(args);
                Log.d("Passing image", String.valueOf(args));
                getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

                toast.show();

            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }

            //refresh camera to continue preview
            mPreview.refreshCamera(mCamera);
        }
    };
    return picture;
}


//make picture and save to a folder
public static File getOutputMediaFile() {
    //make a new file directory inside the "sdcard" folder
    File mediaStorageDir = new File("/sdcard/", "JCG Camera");

    //if this "JCGCamera folder does not exist
    if (!mediaStorageDir.exists()) {
        //if you cannot make this folder return
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    //take the current timeStamp
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    //and make a media file:
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");


    return mediaFile;
}

OnClickListener captrureListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        mCamera.takePicture(null, null, mPicture);
    }
};

private void releaseCamera() {
    // stop and release camera
    if (mCamera != null) {
        mCamera.release();
        mCamera = null;
    }
}

}

1 个答案:

答案 0 :(得分:0)

无论是什么原因,都没有获得相机手柄是需要通过适当的错误处理来处理的情况。在Pause处理程序的当前情况下,是否正在发布Camera实例?检查http://developer.android.com/training/basics/activity-lifecycle/pausing.html

的正确使用情况