package com.example.locationapp
import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
class LocationTrackerScreen : AppCompatActivity() {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var latitudeTextView: TextView
private lateinit var longitudeTextView: TextView
private lateinit var getLocationButton: Button
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
getLastLocation()
} else {
Toast.makeText(this, "Location permission denied", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_tracker)
latitudeTextView = findViewById(R.id.latitudeTextView)
longitudeTextView = findViewById(R.id.longitudeTextView)
getLocationButton = findViewById(R.id.getLocationButton)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getLocationButton.setOnClickListener {
when {
ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED -> {
getLastLocation()
}
else -> {
requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
}
}
}
private fun getLastLocation() {
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
latitudeTextView.text = "Latitude: ${location.latitude}"
longitudeTextView.text = "Longitude: ${location.longitude}"
} else {
Toast.makeText(this, "Location not available", Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener {
Toast.makeText(this, "Failed to get location", Toast.LENGTH_SHORT).show()
}
}
}This solution uses Android's FusedLocationProviderClient to get the last known location.
We check if the app has permission to access fine location. If not, we request it using the Activity Result API, which is the modern way to handle permissions.
When permission is granted, we call getLastLocation() to fetch the location and update the UI TextViews with latitude and longitude.
If permission is denied or location is unavailable, we show a friendly Toast message to inform the user.