Where to put app Permissions code

So I have a button to click that will access the gallery. I need to ask permissions to access Read External Storage. I believe I have the code to do it. Only problem is I have no idea where to place the code. All the “context” that is required seems to have to come from Activity? I think?

The button is in one of my fragments, so how do I get this “context” from there? The code shows no errors when placed in MainActivity, but complains when placed in my fragment section.

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    fun innerCheck(name: String){
        if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "Access denied", Toast.LENGTH_SHORT).show()
        }else {
            //openGallery
        }
    }

    when (requestCode) {
        reqCode -> innerCheck("Storage")
    }
}

private fun checkForPermissions(permission: String, name: String, requestCode: Int){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        when {
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED -> {
                Toast.makeText(this, "Granted", Toast.LENGTH_SHORT).show()
            }
            shouldShowRequestPermissionRationale(this, permission) -> showDialog(permission, name, requestCode)

            else -> ActivityCompat.requestPermissions(this, arrayOf(permission),requestCode)
        }
    }
}

private fun showDialog(permission: String, name: String, requestCode: Int){
    val builder = AlertDialog.Builder(this)

    builder.apply {
        setMessage("Access to storage required")
        setTitle("Permission required")
        setPositiveButton("Ok") { dialog, which ->
            ActivityCompat.requestPermissions(this@Permissions, arrayOf(permission), requestCode)

        }

    }
    val dialog = builder.create()
    dialog.show()
}

You can call getContext() on a Fragment to get a Context. If you specifically need an activity, call getActivity().

Note, though, that both methods may return null if the fragment is not currently associated with an activity. Right at the point of a button click should be safe.