Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

android - How to check if camera is opened by any application

Is there any way to check if the camera is open or not? I don't want to open the camera, I just want to check its status.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your device API version is higher than 21, CameraManager.AvailabilityCallback might be a good choice.

You need to first obtain the camera manager of the system with the following code:

CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

Then, you need to register the AvailabilityCallback:

CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    manager.registerAvailabilityCallback(new CameraManager.AvailabilityCallback() {
        @Override
        public void onCameraAvailable(String cameraId) {
            super.onCameraAvailable(cameraId);
            //Do your work
        }

        @Override
        public void onCameraUnavailable(String cameraId) {
            super.onCameraUnavailable(cameraId);
            //Do your work
        }
    }, yourHandler);
}

This works better if API version is higher than 21. You can refer to CameraManager, CameraManager.AvailabilityCallback, and the whole package

Trying to open the camera to check if exception is thrown works good if API level is lower than 23. In API level 23, camera service is different than before, from the official docs:

Access to camera subsystem resources, including opening and configuring a camera device, is awarded based on the “priority” of the client application process. Application processes with user-visible or foreground activities are generally given a higher-priority, making camera resource acquisition and use more dependable.

Active camera clients for lower priority apps may be “evicted” when a higher priority application attempts to use the camera. In the deprecated Camera API, this results in onError() being called for the evicted client. In the Camera2 API, it results in onDisconnected() being called for the evicted client.

We can see that in API 23 or higher, trying to open the camera used by other app/process will seize the camera from app/process which was using it, instead of getting RuntimeException.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...