-
-
Save c4software/a3fa7f584a464a6308648b7fcce28add to your computer and use it in GitHub Desktop.
ActivityPermissions DEMO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActivityPermissions : AppCompatActivity() { | |
companion object { | |
const val PERMISSION_REQUEST_LOCATION = 9999 | |
fun getStartIntent(context: Context): Intent { | |
return Intent(context, ActivityPermissions::class.java) | |
} | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_permissions) | |
supportActionBar?.apply { | |
setTitle(R.string.locate_me) | |
setDisplayHomeAsUpEnabled(true) | |
setDisplayShowHomeEnabled(true) | |
} | |
findViewById<Button>(R.id.locate).setOnClickListener { | |
requestPermission() | |
} | |
} | |
override fun onSupportNavigateUp(): Boolean { | |
finish() | |
return true | |
} | |
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { | |
super.onRequestPermissionsResult(requestCode, permissions, grantResults) | |
when (requestCode) { | |
PERMISSION_REQUEST_LOCATION -> { | |
// If request is cancelled, the result arrays are empty. | |
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { | |
// Permission obtenue, Nous continuons la suite de la logique. | |
getLocation() | |
} else { | |
// TODO | |
// Permission non accepté, expliqué ici via une activity ou une dialog pourquoi nous avons besoins de la permissions | |
} | |
return | |
} | |
} | |
} | |
@SuppressLint("MissingPermission") | |
private fun getLocation() { | |
if (hasPermission()) { | |
val locationManager = applicationContext.getSystemService(LOCATION_SERVICE) as LocationManager? | |
locationManager?.run { | |
locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)?.run { | |
geoCode(this) | |
} | |
} | |
} | |
} | |
private fun requestPermission() { | |
if (!hasPermission()) { | |
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_LOCATION) | |
} else { | |
getLocation() | |
} | |
} | |
private fun hasPermission(): Boolean { | |
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED | |
} | |
private fun geoCode(location: Location){ | |
val geocoder = Geocoder(this, Locale.getDefault()) | |
val results = geocoder.getFromLocation(location.latitude, location.longitude, 1) | |
val locationText = findViewById<TextView>(R.id.locationText) | |
if (results.isNotEmpty()) { | |
locationText.text = results[0].getAddressLine(0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment