如何临时释放相机?

时间:2015-11-17 07:38:40

标签: android camera android-service

我的应用程序有两个服务将使用相机

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

使用

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

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

@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;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

  

不是将摄像头代码放在两个服务类中,你应该创建一个Camera Util并将你的摄像头代码放在那里并检查那里..你的相机是打开还是关闭......所以你不需要检查你的服务是是否运行..

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