Jecimi
Jecimi

Reputation: 4173

Detect if camera is already open

I'm making an app that use the flashlight of the camera.

I open the camera with :

 Camera cam = Camera.open();

When I start my app, if another app is already using the camera, I get an error :

java.lang.RuntimeException: Fail to connect to camera service

First, is there any way to still use the camera if it has already been opened by another app ?

If it's not possible, I would like my app to display a message "Camera already in use" instead of crashing.

In this case, how can I detect if the camera is already opened by another app ?

Upvotes: 2

Views: 5154

Answers (2)

vikky.rk
vikky.rk

Reputation: 4149

The Android CameraService does not allow two clients to access the Camera at the same time. Even if your device has 2 cameras (front and back) you can operate only 1 of it and through only 1 app at a time. You have no option but to 'exit gracefully' as Sam suggested.

Upvotes: 3

Sam
Sam

Reputation: 86948

If the camera is in use by another application I don't believe there is much you can do until that app releases it one way or another. However you can implement a try-catch block to catch the exception:

try {
    Camera cam = Camera.open();
}
catch(RuntimeException exception) {
    Toast.makeText(this, "The camera and flashlight are in use by another app.", Toast.LENGTH_LONG).show();
    // Exit gracefully
}

Upvotes: 5

Related Questions