Implementation of Location Tracking using Kotlin.

=>Add below permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />

<service

android:name="gkcheckin.webgrid.in.service.LocationService"

android:enabled="true"

android:exported="false"

android:foregroundServiceType="location" />

=> Below is a service to implement location tracking.

class LocationService : Service() {

private val CHANNEL_ID = "ForegroundService Kotlin"

private lateinit var fusedLocationClient: FusedLocationProviderClient

private lateinit var lastLocation: Location

private lateinit var locationCallback: LocationCallback

private lateinit var locationRequest: LocationRequest

private var locationUpdateState = false

private val LOCATION_PERMISSION_REQUEST_CODE = 1

private val REQUEST_CHECK_SETTINGS = 2

private lateinit var sharedPreference: SharedPreference

private lateinit var input: String

var mTimer: Timer? = null

private var notify_interval: Long = 30000

private lateinit var mHandler: Handler

private lateinit var mRunnable: Runnable

=> Below are the functions to start and stop location tracking in background.

companion object {

fun startService(context: Context, message: String) {

val startIntent = Intent(context, LocationService::class.java)

startIntent.putExtra("inputExtra", message)

ContextCompat.startForegroundService(context, startIntent)

}

fun stopService(context: Context, message: String) {

val stopIntent = Intent(context, LocationService::class.java)

stopIntent.putExtra("inputExtra", message)

context.stopService(stopIntent)

}

}


override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

sharedPreference = SharedPreference(this)

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

//do heavy work on a background thread

locationCallback = object : LocationCallback() {

override fun onLocationResult(p0: LocationResult) {

super.onLocationResult(p0)

lastLocation = p0.lastLocation!!

}

}

}

createLocationRequest()

createNotificationChannel()

input = if (!gpsStatus()) {

"You're Offline !, Check your GPS connection."

} else if (!isNetworkAvailable()) {

"You're Offline !, Check your network connection."

} else {

"You're Online !"

}

return START_NOT_STICKY

}

override fun onBind(intent: Intent): IBinder? {

return null

}

private fun startLocationUpdates() {

//1

if (ActivityCompat.checkSelfPermission(

this,

android.Manifest.permission.ACCESS_FINE_LOCATION

) != PackageManager.PERMISSION_GRANTED

) { /*ActivityCompat.requestPermissions(

this,

arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),

LOCATION_PERMISSION_REQUEST_CODE)*/

return

}

//2

fusedLocationClient.requestLocationUpdates(

locationRequest,

locationCallback,

null/*Looper*/

)

}

=> Below function is used for getting location for every interval as we decide.

private fun createLocationRequest() {

locationRequest = LocationRequest()

locationRequest.interval = 10000

locationRequest.fastestInterval = 5000

locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

val builder = LocationSettingsRequest.Builder()

.addLocationRequest(locationRequest)

// 4

val client = LocationServices.getSettingsClient(this)

val task = client.checkLocationSettings(builder.build())

// 5

task.addOnSuccessListener {

locationUpdateState = true

startLocationUpdates()

}

}

private fun requestLocationUpdates() {

if (!gpsStatus()) {

showNotification("You're Offline !, Check your GPS connection.")

} else {

createLocationRequest()

}

}

private fun gpsStatus(): Boolean {

val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)

}

override fun onDestroy() {

try {

fusedLocationClient.removeLocationUpdates(locationCallback)

}catch (e: Exception){

}

super.onDestroy()

}

}

Sign In or Register to comment.