1
+ package com.segment.analytics.next.plugins
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.content.pm.PackageManager
6
+ import android.location.LocationManager
7
+ import android.os.Build
8
+ import com.segment.analytics.kotlin.core.Analytics
9
+ import com.segment.analytics.kotlin.core.BaseEvent
10
+ import com.segment.analytics.kotlin.core.platform.Plugin
11
+ import kotlinx.serialization.json.JsonPrimitive
12
+ import kotlinx.serialization.json.buildJsonObject
13
+ import androidx.core.app.ActivityCompat
14
+
15
+ class PassiveLocationPlugin (val context : Context ): Plugin {
16
+ override lateinit var analytics: Analytics
17
+ override val type: Plugin .Type = Plugin .Type .Enrichment
18
+
19
+ override fun execute (event : BaseEvent ): BaseEvent ? {
20
+
21
+ event.context = buildJsonObject {
22
+
23
+ event.context.forEach { (key, value) ->
24
+ put(key, value)
25
+ }
26
+
27
+ if (ActivityCompat .checkSelfPermission(
28
+ context,
29
+ Manifest .permission.ACCESS_FINE_LOCATION
30
+ ) == PackageManager .PERMISSION_GRANTED || ActivityCompat .checkSelfPermission(
31
+ context,
32
+ Manifest .permission.ACCESS_COARSE_LOCATION
33
+ ) == PackageManager .PERMISSION_GRANTED
34
+ ) {
35
+ val locationManager =
36
+ context.getSystemService(Context .LOCATION_SERVICE ) as LocationManager
37
+
38
+ // Passive Provider is API level 8
39
+ val passiveLastKnownLocation = locationManager.getLastKnownLocation(
40
+ LocationManager .PASSIVE_PROVIDER
41
+ )
42
+
43
+ put(" location" , buildJsonObject {
44
+ put(" lat" , JsonPrimitive (passiveLastKnownLocation?.latitude))
45
+ put(" lon" , JsonPrimitive (passiveLastKnownLocation?.longitude))
46
+ put(" alt" , JsonPrimitive (passiveLastKnownLocation?.altitude))
47
+ put(" acc" , JsonPrimitive (passiveLastKnownLocation?.accuracy))
48
+ put(" bearing" , JsonPrimitive (passiveLastKnownLocation?.bearing))
49
+ put(" provider" , JsonPrimitive (passiveLastKnownLocation?.provider))
50
+ put(" speed" , JsonPrimitive (passiveLastKnownLocation?.speed))
51
+
52
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
53
+ put(" acc" , JsonPrimitive (passiveLastKnownLocation?.verticalAccuracyMeters))
54
+ put(
55
+ " BearingAcc" ,
56
+ JsonPrimitive (passiveLastKnownLocation?.bearingAccuracyDegrees)
57
+ )
58
+ }
59
+
60
+
61
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .TIRAMISU ) {
62
+ put(
63
+ " elapsedRealtimeAgeMillis" ,
64
+ JsonPrimitive (passiveLastKnownLocation?.elapsedRealtimeAgeMillis)
65
+ )
66
+ put(
67
+ " elapsedRealtimeMillis" ,
68
+ JsonPrimitive (passiveLastKnownLocation?.elapsedRealtimeMillis)
69
+ )
70
+ put(" isMock" , JsonPrimitive (passiveLastKnownLocation?.isMock))
71
+ }
72
+ })
73
+ } else {
74
+ put(" location" , JsonPrimitive (" n/a" ))
75
+ }
76
+
77
+ }
78
+
79
+
80
+ return event
81
+ }
82
+ }
0 commit comments