From b5bfe7d968f00c48180b1b4c4c18766b44f059c2 Mon Sep 17 00:00:00 2001 From: hicham Date: Sat, 30 Oct 2021 13:08:04 +0100 Subject: [PATCH] Add location observer --- app/build.gradle | 5 +- app/src/main/AndroidManifest.xml | 3 + .../hicham/flowlifecycle/LocationObserver.kt | 55 +++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/hicham/flowlifecycle/LocationObserver.kt diff --git a/app/build.gradle b/app/build.gradle index 800c61c..b378aea 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -8,7 +8,7 @@ android { defaultConfig { applicationId "com.hicham.flowlifecycle" - minSdk 21 + minSdk 23 targetSdk 31 versionCode 1 versionName "1.0" @@ -37,6 +37,9 @@ dependencies { implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' + implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0" + implementation "androidx.fragment:fragment-ktx:1.3.6" + implementation 'com.google.android.gms:play-services-location:18.0.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2" testImplementation 'junit:junit:4.13.2' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c717771..c7f8d99 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,9 @@ + + + { + return callbackFlow { + Log.d(TAG, "observing location updates") + + val client = LocationServices.getFusedLocationProviderClient(context) + val locationRequest = LocationRequest + .create() + .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) + .setInterval(0) + .setFastestInterval(0) + + val locationCallback = object : LocationCallback() { + override fun onLocationResult(locationResult: LocationResult?) { + if (locationResult != null) { + Log.d(TAG, "got location ${locationResult.lastLocation}") + trySend(locationResult.lastLocation) + } + } + } + + client.requestLocationUpdates( + locationRequest, + locationCallback, + Looper.getMainLooper() + ) + + awaitClose { + Log.d(TAG, "stop observing location updates") + client.removeLocationUpdates(locationCallback) + } + } + } +} \ No newline at end of file