我想创建服务,我可以在其中打开相机。 如果相机已打开,我想用相机拍摄照片。
请帮我这样做。
我尝试跟踪获取状态,但我总是得到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=====");
}
答案 0 :(得分:1)
Camera.open()
会给你一个例外。
来自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
}
更新
如果其他应用已经打开相机,相机将暂停时从该应用中释放(除非其他应用在后台使用相机使用服务等)。
答案 1 :(得分:0)
你可以使用这个逻辑......
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;
}
首先尝试打开相机..它成功打开,这意味着它已关闭。 如果捕获异常意味着它已启用或由其他应用程序累积...最后您需要释放摄像头否则您无法再次打开它... 然后在您的清单文件中添加一些权限,例如
<?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>