1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FusedLocationProviderClientのLastLocationがnullになる

Last updated at Posted at 2021-03-11

FusedLocationProviderClientLastLocationnullになってしまう現象に遭遇したので、原因と解決方法を書きたいと思います。

nullのときはrequestLocationUpdates

LastLocationnullのときはfusedLocationProviderClient.requestLocationUpdates()を呼び出して、位置情報を取得します。


val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context)

fusedLocationProviderClient.lastLocation.addOnSuccessListener { location: Location? ->
            
  location ?: run {
    val request = LocationRequest.create().apply {
      interval = 5000
          fastestInterval = 3000
          priority = LocationRequest.PRIORITY_HIGH_ACCURACY
      }
       fusedLocationProviderClient.requestLocationUpdates(
      request,
          object : LocationCallback() {
            override fun onLocationResult(result: LocationResult) {
          super.onLocationResult(result)

          val lastLocation = result.lastLocation
	  
	      // 何か処理を行う
          _current = LatLng(lastLocation.latitude, lastLocation.longitude)
	  
          // 一度だけ位置情報が取得出来ればいいので、取得後は位置情報の更新を停止する。
          fusedLocationProviderClient.removeLocationUpdates(this)
              }
          }, Looper.getMainLooper())
  }
}

なぜnullになるのか?

再起動後など端末が一度も位置情報を取得していないときに発生します。
なので、GoogleMapを起動して位置情報を取得すると、LastLocationがちゃんと返ってくるようになります。

まとめ

端末を再起動したことを忘れて「あれ...?なんでnullになるんだ...」とハマってしまうことがよくあったので、今回書いてみました(笑)

誰かのお役に立てれば幸いです٩( 'ω' )و

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?