Skip to content

Examples

Basic tracking

import com.transistorsoft.locationmanager.kotlin.BGGeo
import com.transistorsoft.locationmanager.kotlin.config.DesiredAccuracy
import com.transistorsoft.locationmanager.kotlin.config.LogLevel

// Application.onCreate() — initialize once
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        BGGeo.init(this)
    }
}

// Activity / Fragment — call ready() in a coroutine scope
class MainActivity : AppCompatActivity() {
    private val subscriptions = mutableSetOf<EventSubscription>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bgGeo = BGGeo.instance
        bgGeo.setActivity(this)

        // Register event listeners *before* calling ready()
        bgGeo.onLocation { event ->
            Log.d(TAG, "[onLocation] ${event.coords}")
        }.storeIn(subscriptions)

        lifecycleScope.launch {
            // ready() configures the SDK and restores persisted state.
            // It does NOT start tracking — call start()/stop() separately.
            bgGeo.ready {
                geolocation.desiredAccuracy = DesiredAccuracy.HIGH
                geolocation.distanceFilter = 10f
                app.stopOnTerminate = false
                app.startOnBoot = true
                logger.debug = true
                logger.logLevel = LogLevel.VERBOSE
            }
        }
    }

    // Elsewhere — e.g. a toggle-button click listener in your UI
    private fun onToggleTracking() {
        lifecycleScope.launch {
            val bgGeo = BGGeo.instance
            val state = bgGeo.state
            if (state.enabled) {
                bgGeo.stop()
            } else {
                bgGeo.start()
            }
            Log.d(TAG, "[state] enabled=${state.enabled} trackingMode=${state.trackingMode}")
        }
    }

    override fun onDestroy() {
        subscriptions.forEach { it.close() }
        subscriptions.clear()
        super.onDestroy()
    }
}