0

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?

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • Compiler is not able to determine that your function actually checks the permission. If you exclude the method and check permission in-line, it works. – Pawel May 16 '19 at 00:15
  • @zorgan which location services version are you using ? – Nisarg May 16 '19 at 13:21
  • I'm using `com.google.android.gms:play-services-location:16.0.0` - does that answer your question? @Nisarg – Zorgan May 17 '19 at 01:13

0 Answers0