May 12, 2024

Check Camera is Accessed By Other App in kotlin

We are create one Context function with a call back in kotlin, Using this function you can find is camera accessed by other app or not,


Function calling,

context.isCameraAccessedByOtherApp { accessed ->
if(accessed){

 
}else{

}
}


Function to check is camera accessed by other application

fun Context.isCameraAccessedByOtherApp(callback:(Boolean) -> Unit){
    try {
        val manager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val allCameraIds: Array<String> = manager.cameraIdList
        val busyCams = mutableListOf<String>()
        val availableCams = mutableListOf<String>()
        fun check(){
            if((busyCams.size + availableCams.size) == allCameraIds.size){
                callback(busyCams.isNotEmpty())
            }
        }
        manager.registerAvailabilityCallback(
            object: CameraManager.AvailabilityCallback(){
                override fun onCameraAvailable(cameraId: String) {
                    super.onCameraAvailable(cameraId)
                    availableCams.add(cameraId)
                    check()
                }
                override fun onCameraUnavailable(cameraId: String) {
                    super.onCameraUnavailable(cameraId)
                    busyCams.add(cameraId)
                    check()
                }
            },
            Handler(Looper.getMainLooper())
        )
    } catch (e: CameraAccessException) {
        callback(false)
    }
}