Reputation: 178
I want to create service in which I can get camera is opened or not. If there is camera already open I want to capture photo using camera.
Please help me to do this.
I tried following for get status but in that I always get STATUS_ON.
Camera _camera;
boolean qOpened = false;
try {
_camera=Camera.open();
qOpened=(_camera!=null);
if(qOpened){
Camera_status = "STATUS_OFF";
}else{
System.out.println("==nothing to do====");
}
} catch (Exception e) {
Camera_status = "STATUS_ON";
System.out.println("=====Camera running=====");
}
Upvotes: 0
Views: 2507
Reputation: 2188
You can use this logic....
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
Log.e("Camera", "Status_off"); /// it was off
Toast.makeText(this, "Now On", Toast.LENGTH_SHORT).show();
} catch (RuntimeException e) {
Log.e("Camera", "Status_off"); /// it was on
Toast.makeText(this, "Now Off", Toast.LENGTH_SHORT).show();
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
At first try to open camera.. it it successfully open that means it was off. If catch exception that means it is on or accrued by other app...finally you need to release camera otherwise you cannot open it again.. Then add some permission in your manifest file like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorial.jolpai.camera" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Upvotes: 0
Reputation: 3831
Camera.open()
will give you an Exception if Camera is in use.
From the docs,
/** 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
}
UPDATE
if other app had already opened camera, camera will be released from that app once it pauses (except the case that other app uses the camera in the background using service etc).
Upvotes: 1