1
1
package com.segment.analytics.next.plugins
2
2
3
3
import android.Manifest
4
+ import android.annotation.SuppressLint
4
5
import android.content.Context
5
6
import android.content.pm.PackageManager
6
7
import android.location.LocationManager
@@ -12,34 +13,42 @@ import kotlinx.serialization.json.JsonPrimitive
12
13
import kotlinx.serialization.json.buildJsonObject
13
14
import androidx.core.app.ActivityCompat
14
15
15
- class PassiveLocationPlugin (val context : Context ): Plugin {
16
+ /* *
17
+ * The PassiveLocationPlugin will add location information to `event.context.location` if the host
18
+ * app is granted Fine or Coarse location.
19
+ *
20
+ * This plugin will not cause the app the request permission, the host app must implement that logic.
21
+ */
22
+ class PassiveLocationPlugin (val context : Context ) : Plugin {
16
23
override lateinit var analytics: Analytics
17
24
override val type: Plugin .Type = Plugin .Type .Enrichment
18
25
26
+
19
27
override fun execute (event : BaseEvent ): BaseEvent ? {
20
28
29
+ // Update the context property
21
30
event.context = buildJsonObject {
22
31
32
+ // Add all existing context properties
23
33
event.context.forEach { (key, value) ->
24
34
put(key, value)
25
35
}
26
36
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
37
+ // If we have Location Permission (Fine or Coarse)
38
+ if (haveAnyLocationPermission()
34
39
) {
40
+
41
+
35
42
val locationManager =
36
43
context.getSystemService(Context .LOCATION_SERVICE ) as LocationManager
37
44
45
+ @SuppressLint(" MissingPermission" )
38
46
// Passive Provider is API level 8
39
47
val passiveLastKnownLocation = locationManager.getLastKnownLocation(
40
48
LocationManager .PASSIVE_PROVIDER
41
49
)
42
50
51
+ // Build top-level event.context.location object.
43
52
put(" location" , buildJsonObject {
44
53
put(" lat" , JsonPrimitive (passiveLastKnownLocation?.latitude))
45
54
put(" lon" , JsonPrimitive (passiveLastKnownLocation?.longitude))
@@ -71,12 +80,22 @@ class PassiveLocationPlugin(val context: Context): Plugin {
71
80
}
72
81
})
73
82
} else {
83
+ // If we don't have permissions then just set event.context.location = "n/a"
74
84
put(" location" , JsonPrimitive (" n/a" ))
75
85
}
76
-
77
86
}
78
87
79
-
80
88
return event
81
89
}
90
+
91
+ /* *
92
+ * Returns true if we have either Fine or Coarse Location Permission.
93
+ */
94
+ private fun haveAnyLocationPermission () = ActivityCompat .checkSelfPermission(
95
+ context,
96
+ Manifest .permission.ACCESS_FINE_LOCATION
97
+ ) == PackageManager .PERMISSION_GRANTED || ActivityCompat .checkSelfPermission(
98
+ context,
99
+ Manifest .permission.ACCESS_COARSE_LOCATION
100
+ ) == PackageManager .PERMISSION_GRANTED
82
101
}
0 commit comments