我的应用有两个服务将使用相机
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;
}
关于android - 如何临时释放相机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751482/