Rockb
Rockb

Reputation: 43

Android Kotlin update position

I am working on my first Android project. I can pull the last GPS location but when I move the position does not update. If I switch to the maps app then back to my app the GPS location will update so this tells me I need to somehow query the system to update the current location but have not been able to figure out how to do that.

What am I missing?

Below is what I am currently using.

class MainActivity : AppCompatActivity() {

    private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
    private lateinit var tvLatitude:TextView
    private lateinit var tvLongitude:TextView

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

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        tvLatitude=findViewById(R.id.tvLat)
        tvLongitude=findViewById(R.id.tvLon)


        val cmdUpdateLocation = findViewById<Button>(R.id.cmdUpdateLocation)

        cmdUpdateLocation?.setOnClickListener()
        {
            getCurrentLocation()
        }
        
        getCurrentLocation()
    }

    private fun getCurrentLocation() {
        if(checkPermissions())
        {
            if(isLocationEnabled())
            {
                //FInal lat and lon
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    requestPermission()
                    return
                }
                fusedLocationProviderClient.lastLocation.addOnCompleteListener(this){ task->
                    val location: Location?=task.result
                    if(location==null)
                    {
                        Toast.makeText(applicationContext,"Nul received",Toast.LENGTH_SHORT).show()
                    }
                    else
                    {
                        Toast.makeText(applicationContext,"Get Success",Toast.LENGTH_SHORT).show()
                        tvLatitude.text=""+location.latitude
                        tvLongitude.text=""+location.longitude
                    }
                }
            }
            else
            {
                //Settings Open
                Toast.makeText(applicationContext,"Turn on Location",Toast.LENGTH_SHORT).show()
                val intent=Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivity(intent)

            }
        }
        else
        {
                //Request Permission here
            requestPermission()

        }

    }


    private fun isLocationEnabled():Boolean{
        var locationManager:LocationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(
            LocationManager.GPS_PROVIDER
        )
    }

    private fun requestPermission() {
        ActivityCompat.requestPermissions(
            this,arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSION_REQUEST_ACCESS_LOCATION
        )
    }

    companion object{
            private const val PERMISSION_REQUEST_ACCESS_LOCATION=100
        }

    private fun checkPermissions():Boolean
    {
        if(ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_COARSE_LOCATION)
            ==PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
                return true
        }
            return false
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if(requestCode== PERMISSION_REQUEST_ACCESS_LOCATION)
        {
            if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(applicationContext,"Granted",Toast.LENGTH_SHORT).show()
                getCurrentLocation()
            }
            else
            {
                Toast.makeText(applicationContext,"Denied",Toast.LENGTH_SHORT).show()
            }
        }
    }
}

Upvotes: 0

Views: 153

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93678

You need to call requestLocationUpdates, not lastLocation. lastLocation only returns the last known location once, and frequently returns null (if location wasn't on). It does not turn location on.

Upvotes: 1

Related Questions