Search code examples
javaandroidandroid-camerasurfaceviewandroid-permissions

Where to place request permission for camera?


I need to request camera and location permission in some activity that show the camera preview in surfaceview.

Where do I need to put the request permission function? onCreate, onResume, or onSurfaceCreated?

And where do I need to setup the camera?


Solution

  • See asking permission directly corresponds to the app crash if the service is requested and the permission is not available. I would prefer to put the permission in onResume because whatever user action become i.e. like minimizing or a battery low dialog comes on top of screen, we need to check the permission changes again so that you activity changes might have occured through what ever reasons. Either camera is trying to open after network request or what the situation be.

    Put the camera check permission in onResume.

    So lets talk about how would you do it. There are a number of perceptions. What I prefer to do is I create a Helper class that would let me know the permission status with this code

    class PermissionsHelper(activity: Activity) {
    private val activity: Context
    
    init { this.activity = activity }
    
    fun isCameraPermissionAvailable()=ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
    

    }

    }

    So in your activity's onResume method check if the permission is available else request the permission.

     override fun onResume() {
        super.onResume()
        if (!PermissionsHelper(this).isCameraPermissionAvailable()) {
            requestPermissions(arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE)
        }
    }
    

    Also please note two points

    1) You should write permission for camera in manifeast so that app can request the permission
    2) Check if the camera permission is available or not before opening the camera, if not you should again request for the permission
    

    (same as in onResume stage)