Institute of Computer Science
  1. Courses
  2. 2021/22 fall
  3. Mobile Computing and Internet of Things (LTAT.06.009)
ET
Log in

Mobile Computing and Internet of Things 2021/22 fall

  • Main
  • Lectures
  • Labs
  • Homeworks & Assignments
  • Results
  • Task submission
  • Extra Materials
  • Best Practices
  • Projects
    • Teams & Topics
    • Presentations & Report
package ee.ut.cs.lab7base

import android.annotation.SuppressLint
import android.content.Context
import android.os.Looper
import com.google.android.gms.location.*
import com.google.android.gms.tasks.Task

class LocationHelper(private val mContext: Context) {

    // !NB Don't forget to add 'play-services-location' gradle dependency!

    private val locationRequest = LocationRequest.create().apply {
        interval = 10000
        fastestInterval = 5000
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }

    var registeredCallbacks: ArrayList<LocationCallback> = arrayListOf()

    fun requestLocationUpdates( callback: LocationCallback) {
        val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
        val client: SettingsClient = LocationServices.getSettingsClient(mContext)
        val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

        task.addOnSuccessListener {
            // All location settings are satisfied. The client can initialize location requests here.
            startLocationUpdates(callback)
        }

        task.addOnFailureListener { exception ->
            // lacking permissions //TODO
        }
    }

    @SuppressLint("MissingPermission")
    private fun startLocationUpdates(callback: LocationCallback) {
        val fusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext)
        fusedLocationClient.requestLocationUpdates(locationRequest,
            callback,
            Looper.getMainLooper())
        registeredCallbacks.add(callback)

    }

    fun stopLocationUpdates(){
        registeredCallbacks.forEach {
            LocationServices.getFusedLocationProviderClient(mContext)
                .removeLocationUpdates(it)
        }
        registeredCallbacks.clear()
    }

}

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment