Skip to content

Commit

Permalink
Update comments on the PassiveLocationPlugin. (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
didiergarcia authored Oct 25, 2023
1 parent c4e4d13 commit 95c00bf
Showing 1 changed file with 29 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.segment.analytics.next.plugins

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
Expand All @@ -12,34 +13,42 @@ import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import androidx.core.app.ActivityCompat

class PassiveLocationPlugin(val context: Context): Plugin {
/**
* The PassiveLocationPlugin will add location information to `event.context.location` if the host
* app is granted Fine or Coarse location.
*
* This plugin will not cause the app the request permission, the host app must implement that logic.
*/
class PassiveLocationPlugin(val context: Context) : Plugin {
override lateinit var analytics: Analytics
override val type: Plugin.Type = Plugin.Type.Enrichment


override fun execute(event: BaseEvent): BaseEvent? {

// Update the context property
event.context = buildJsonObject {

// Add all existing context properties
event.context.forEach { (key, value) ->
put(key, value)
}

if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
// If we have Location Permission (Fine or Coarse)
if (haveAnyLocationPermission()
) {


val locationManager =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

@SuppressLint("MissingPermission")
// Passive Provider is API level 8
val passiveLastKnownLocation = locationManager.getLastKnownLocation(
LocationManager.PASSIVE_PROVIDER
)

// Build top-level event.context.location object.
put("location", buildJsonObject {
put("lat", JsonPrimitive(passiveLastKnownLocation?.latitude))
put("lon", JsonPrimitive(passiveLastKnownLocation?.longitude))
Expand Down Expand Up @@ -71,12 +80,22 @@ class PassiveLocationPlugin(val context: Context): Plugin {
}
})
} else {
// If we don't have permissions then just set event.context.location = "n/a"
put("location", JsonPrimitive("n/a"))
}

}


return event
}

/**
* Returns true if we have either Fine or Coarse Location Permission.
*/
private fun haveAnyLocationPermission() = ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}

0 comments on commit 95c00bf

Please sign in to comment.