如何临时释放相机?

How to release camera temporary?

我的应用有两个服务将使用摄像头

Service2 会抛出异常,因为相机正在被 Service1

使用

但是我发现了一些相机应用,当其他应用打开相机时,它会暂时释放相机,直到其他应用完成

如何让Service1在Service2打开相机时可以释放相机?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent1 = new Intent(getApplicationContext(), Service1.class);
    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startService(intent1);
    Intent intent2 = new Intent(getApplicationContext(), Service2.class);
    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startService(intent2);
}

public class Service1 extends Service {
    Camera camera;

    public Service1() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            camera = Camera.open();
        }catch(Exception e){
            Log.e("service1", "open camera error");
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(camera!=null) {
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
            camera = null;
        }
    }
}

public class Service2 extends Service {

    Camera camera;

    public Service2() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            camera = Camera.open();
        }catch(Exception e){
            Log.e("service2", "open camera error");
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(camera!=null) {
            camera.stopPreview();
            camera.setPreviewCallback(null);
            camera.release();
            camera = null;
        }
    }
}

Rather than puting Camera code in both service class you should create a Camera Util and put your camera code there and check there.. is your camera is on or off..so you don't need to check is your service is running or not..

public boolean isCameraUsebyApp() {
    Camera camera = null;
    try {
        camera = Camera.open();
    } catch (RuntimeException e) {
        return true;
    } finally {
        if (camera != null) camera.release();
    }
    return false;
}