Skip to content

Instantly share code, notes, and snippets.

@Lavanyagaur22
Created April 26, 2020 14:43
Show Gist options
  • Save Lavanyagaur22/96aa78dd8104a77826f45eca54baf0c8 to your computer and use it in GitHub Desktop.
Save Lavanyagaur22/96aa78dd8104a77826f45eca54baf0c8 to your computer and use it in GitHub Desktop.
...
try {
fusedLocationProviderClient.requestLocationUpdates(
locationRequest, locationCallback, Looper.myLooper())
} catch (se: SecurityException) {
Log.e(TAG, "Lost location permissions. Couldn't remove updates. $se")
//Create a function to request necessary permissions from the app.
checkAndStartLocationUpdates()
}
...
private fun checkAndStartLocationUpdates(){
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(
this, //instance of current activity that is trying to subscribe to get location changes
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE
),
LOCATION_REQ //A Constant showing the request to get access to location permissions
)
}else{
//retry to subscribe to location changes
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == LOCATION_REQ){
for(i in grantResults.indices){
if (grantResults[i]!= PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Please Give ${permissions[i]}",Toast.LENGTH_LONG).show()
return
}
}
//retry to subscribe to location changes
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment