Search code examples
androidkotlingeolocationgoogle-play-servicesandroid-gps

Updating the GPS position of a device in an Android app


I have a tiny Android app written in kotlin, it gets the location of the device. All the code is below. I am following this document https://developer.android.com/training/location/request-updates in order to implement updating the GPS position. But I only get the lastLocation once.

class MainActivity : AppCompatActivity() {
    lateinit var locationRequest: LocationRequest
    lateinit var locationCallback: LocationCallback

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        gpsPermissionCheck()

        val client = LocationServices.getFusedLocationProviderClient(this)

        client.lastLocation.addOnSuccessListener { location : Location? ->
            location?.let {
                println("We now have the location!")
                println("Latitude:"+it.latitude.toString()+"   Longitude:"+it.longitude.    toString())
                val compoID = resources.getIdentifier("txtlabel","id",packageName)
                val theLabel = findViewById<TextView>(compoID)
                theLabel.text = "Latit: "+it.latitude.toString()+"   Longit:"+it.longitude. toString()
            }
        }

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

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                locationResult ?: return
                for (location in locationResult.locations){
                    // Update UI with location data
                    // ...
                }
            }
        }
    }


    fun gpsPermissionCheck() {
        try {
            if (ContextCompat.checkSelfPermission(
                    applicationContext,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    101
                )
            } else {
                //locationStart()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    } /* End of gpsPermissionCheck */
}

When I add the block of code:

locationCallback = object : LocationCallback() {...}

I get this error message:

'onLocationResult' overrides nothing

Solution

  • Updated Answer

    Step1:

    Add manifest permissions

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

    Step2:

    Add your activity

    companion object{
        private const val UPDATE_INTERVAL_IN_MILLISECONDS = 10000L
        private const val FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2
    }
    private lateinit var  mFusedLocationClient :FusedLocationProviderClient
    

    init client onCreate function

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    

    Step3:

    Create this callback on the top

    private val mCallBack = object: LocationCallback(){
        override fun onLocationResult(p0: LocationResult) {
            Log.d(TAG, "onLocationResult: $p0")
            super.onLocationResult(p0)
        }
    
        override fun onLocationAvailability(p0: LocationAvailability) {
            Log.d(TAG, "onLocationAvailability: $p0")
            super.onLocationAvailability(p0)
        }
    
    }
    

    Step4:

    Create location updates

    private fun createLocationRequest() = LocationRequest.create().apply {
           interval = UPDATE_INTERVAL_IN_MILLISECONDS
           fastestInterval = FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS
           priority = Priority.PRIORITY_HIGH_ACCURACY
    }
    
    @SuppressLint("MissingPermission")
    fun requestLocationUpdates() {
        try {
            mFusedLocationClient.requestLocationUpdates(
                createLocationRequest(),
                mCallBack, Looper.myLooper()
            )
        } catch (ex: SecurityException) {
            Log.e(TAG, "Lost location permission. Could not request updates. $ex")
        }
    }
    

    Step5:

    REQUEST RUN TIME PERMISSION

    Permission succeed call this method

    requestLocationUpdates()
    

    Step6:

    When you want to stop call this method

    private fun removeLocationUpdates() {
        try {
            mFusedLocationClient.removeLocationUpdates(mCallBack)
    
        } catch (ex : SecurityException) {
            Log.e(TAG, "Lost location permission. Could not remove updates. $ex")
        }
    }