I understand you need to check if the user has allowed location before performing methods on fusedLocationProviderClient
. So I created a global method like so:
fun locationAllowed(context: Context): Int {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
return PackageManager.PERMISSION_GRANTED
}
return PackageManager.PERMISSION_DENIED
}
and used it in my activity:
class Home : FragmentActivity() {
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
if (locationAllowed(this) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.lastLocation // still gives me the error
}
}
}
however I'm still getting a red underline on fusedLocationProviderClient.lastLocation
: Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException.
Any idea why?