アプリ開発備忘録

PlayStationMobile、Android、UWPの開発備忘録

【ACCESS_COARSE_LOCATION】おおよその位置情報にちゃんと対応する

詳細な位置情報 ACCESS_FINE_LOCATION を取得しようとしても、 ACCESS_FINE_LOCATION ではなく、大まかな位置情報である ACCESS_COARSE_LOCATION が許可される場合があるので、しっかりチェックしましょう。

MainActivity.kt

private val launcher = object {
    private val launcher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { fineGranted ->
        val coarseGranted = ActivityCompat.checkSelfPermission(
            this@MainActivity, Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        if (fineGranted || coarseGranted) {
            TODO()
        }
    }

    fun launch() {
        launcher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    launcher.launch()
}

後は普通に位置情報を取得するだけ。

@RequiresPermission(anyOf = ["android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"])
suspend fun getLastLocation(): Location? = suspendCoroutine { suspendCoroutine ->
    LocationServices.getFusedLocationProviderClient(context).lastLocation
        .addOnSuccessListener {
            suspendCoroutine.resume(it)
        }
        .addOnFailureListener {
            suspendCoroutine.resume(lastLocation)
        }
        .addOnCanceledListener {
            suspendCoroutine.resume(lastLocation)
        }
}