Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 3, 2021 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/fb06d983dd0189991e773aa1d7a45199 to your computer and use it in GitHub Desktop.
Save parzibyte/fb06d983dd0189991e773aa1d7a45199 to your computer and use it in GitHub Desktop.
package me.parzibyte.algunproyecto
import android.Manifest
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat
class EnviarUbicacionService : Fragment() {
private val CODIGO_PERMISOS_UBICACION_SEGUNDO_PLANO = 2106
private val LOG_TAG = "EnviarUbicacion"
private var haConcedidoPermisos = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
verificarPermisos()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_enviar_ubicacion_service, container, false)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == CODIGO_PERMISOS_UBICACION_SEGUNDO_PLANO) {
val todosLosPermisosConcedidos =
grantResults.all { it == PackageManager.PERMISSION_GRANTED }
if (grantResults.isNotEmpty() && todosLosPermisosConcedidos) {
haConcedidoPermisos = true;
Log.d(LOG_TAG, "El usuario concedió todos los permisos")
} else {
Log.d(LOG_TAG, "Uno o más permisos fueron denegados")
}
}
}
private fun verificarPermisos() {
val permisos = arrayListOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
)
// Segundo plano para Android Q
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
permisos.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}
val permisosComoArray = permisos.toTypedArray()
if (tienePermisos(permisosComoArray)) {
haConcedidoPermisos = true
Log.d(LOG_TAG, "Los permisos ya fueron concedidos")
} else {
solicitarPermisos(permisosComoArray)
}
}
private fun solicitarPermisos(permisos: Array<String>) {
Log.d(LOG_TAG, "Solicitando permisos...")
requestPermissions(
permisos,
CODIGO_PERMISOS_UBICACION_SEGUNDO_PLANO
)
}
private fun tienePermisos(permisos: Array<String>): Boolean {
return permisos.all {
return ContextCompat.checkSelfPermission(
requireActivity(),
it
) == PackageManager.PERMISSION_GRANTED
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment