Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Android Permissions Helper Functions

I have an activity that requires camera permission.

this activity can be called from several user configurable places in the app.

The rationale dialog and permission dialog themselves should be shown before the activity opens.

idea

right now I am trying to handle these dialogs in some kind of extension function.

fun handlePermissions(context: Context, required_permissions: Array<String>, activity: FragmentActivity?, fragment: Fragment?): Boolean {
    var isGranted = allPermissionsGranted(context, required_permissions)
    if (!isGranted) {
        //null here is where I used to pass my listener which was the calling fragment previously that implemented an interface
        val dialog = DialogPermissionFragment(null, DialogPermissionFragment.PermissionType.QR)


        activity?.supportFragmentManager?.let { dialog.show(it, "") }

        //get result from dialog? how?

        //if accepted launch actual permission request
        fragment?.registerForActivityResult(ActivityResultContracts.RequestPermission()) { success ->
            isGranted = success
        }?.launch(android.Manifest.permission.CAMERA)
    }
    return isGranted
}

But I am having trouble to get the dialog results back from the rationale/explanation dialog.

My research until now brought me to maybe using a higher order function, to pass a function variable to the dialog fragment that returns a Boolean value to the helper function. But I am absolutely unsure if thats the right thing.

I thought using my own code would be cleaner and less overhead, could I achieve this easier when using a framework like eazy-permissions? (is Dexter still recommendable since its no longer under development)

is that even a viable thing I am trying to achieve here?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

One approach that I've implemented and seems viable to use is this:

Class PermissionsHelper

class PermissionsHelper(private val activity: Activity) {

fun requestPermissionsFromDevice(
    arrayPermissions: Array<String>, permissionsResultInterface: PermissionsResultInterface
) {
    setPermissionResultInterface(permissionsResultInterface)
    getMyPermissionRequestActivity().launch(arrayPermissions)
}

fun checkPermissionsFromDevice(permission: String): Boolean {
    return ContextCompat.checkSelfPermission(activity, permission) ==
            PackageManager.PERMISSION_GRANTED
}

}

Class PermissionsResultInterface to the helper class be able to communicate with the activity.

interface PermissionsResultInterface {
    fun onPermissionFinishResult(permissions: MutableMap<String, Boolean>)
}

Usage with this approach to remove all files from app directory:

private fun clearFiles(firstCall: Boolean = false) {
    if (verifyStoragePermissions(firstCall)) {
        val dir = File(getExternalFilesDir(null).toString())
        removeFileOrDirectory(dir)
        Toast.makeText(
            applicationContext,
            resources.getString(R.string.done),
            Toast.LENGTH_SHORT
        ).show()
    }
}

private fun verifyStoragePermissions(firstCall: Boolean = false): Boolean {
    val arrayListPermissions = arrayOf(
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    for (permission in arrayListPermissions) {
        if (!PermissionsHelper(this).checkPermissionsFromDevice(permission)) {
            if (firstCall) PermissionsHelper(this)
                .requestPermissionsFromDevice(arrayListPermissions, this)
            else PermissionsDialogs(this).showPermissionsErrorDialog()
            return false
        }
    }
    return true
}

override fun onPermissionFinishResult(permissions: MutableMap<String, Boolean>) {
    clearFiles()
}

With this approach you are able to call the permissions helper and using the result interface, after each of the answers from user, decide wether you still need to make a call for permissions or show a dialog to him.

If you need any help don't hesitate to contact me.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda