Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}