Skip to content

Commit 3a65ff2

Browse files
authored
Update passive location plugin 2 (#198)
* Don't set the event.context.location property to anything if we don't have location permissions. * Refactor getting last location into function.
1 parent fd36a96 commit 3a65ff2

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

samples/kotlin-android-app/src/main/java/com/segment/analytics/next/plugins/PassiveLocationPlugin.kt

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import android.Manifest
44
import android.annotation.SuppressLint
55
import android.content.Context
66
import android.content.pm.PackageManager
7+
import android.location.Location
78
import android.location.LocationManager
89
import android.os.Build
910
import com.segment.analytics.kotlin.core.Analytics
@@ -38,15 +39,7 @@ class PassiveLocationPlugin(val context: Context) : Plugin {
3839
if (haveAnyLocationPermission()
3940
) {
4041

41-
42-
val locationManager =
43-
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
44-
45-
@SuppressLint("MissingPermission")
46-
// Passive Provider is API level 8
47-
val passiveLastKnownLocation = locationManager.getLastKnownLocation(
48-
LocationManager.PASSIVE_PROVIDER
49-
)
42+
val passiveLastKnownLocation = getLastKnownLocation()
5043

5144
// Build top-level event.context.location object.
5245
put("location", buildJsonObject {
@@ -65,8 +58,7 @@ class PassiveLocationPlugin(val context: Context) : Plugin {
6558
JsonPrimitive(passiveLastKnownLocation?.bearingAccuracyDegrees)
6659
)
6760
}
68-
69-
61+
7062
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
7163
put(
7264
"elapsedRealtimeAgeMillis",
@@ -85,6 +77,18 @@ class PassiveLocationPlugin(val context: Context) : Plugin {
8577
return event
8678
}
8779

80+
private fun getLastKnownLocation(): Location? {
81+
val locationManager =
82+
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
83+
84+
@SuppressLint("MissingPermission")
85+
// Passive Provider is API level 8
86+
val passiveLastKnownLocation = locationManager.getLastKnownLocation(
87+
LocationManager.PASSIVE_PROVIDER
88+
)
89+
return passiveLastKnownLocation
90+
}
91+
8892
/**
8993
* Returns true if we have either Fine or Coarse Location Permission.
9094
*/

0 commit comments

Comments
 (0)