Add dependency in gradle.app
implementation 'com.google.android.gms:play-services-location:21.0.1'
Kotlin
You can get user's current location by using FusedLocationProviderClient as follow
private lateinit var fusedLocationClient: FusedLocationProviderClient
In your onCreate() method
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.id.activity_main)
// Initialize object
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getCurrentLocation()
}
Last location returns the most recent historical location currently available.
private fun getCurrentLocation() {
// Checking Location Permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
resultLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
return
}
fusedLocationClient.getLastLocation().addOnSuccessListener(this, OnSuccessListener { location: Location? ->
if (location != null) {
val lat = location.latitude
val lon = location.longitude
}
})
}
private val resultLauncher = registerForActivityResult<String, Boolean>(RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
getCurrentLocation()
} else {
Toast.makeText(this, "Location permission not granted", Toast.LENGTH_SHORT).show()
}
}
Java
private FusedLocationProviderClient fusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.id.activity_main)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
getCurrentLocation();
}
private void getCurrentLocation() {
// Checking Location Permission
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
resultLauncher.launch(android.Manifest.permission.ACCESS_FINE_LOCATION);
return;
}
fusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
if (location != null) {
double lat = location.getLatitude();
double lon = location.getLongitude();
}
});
}
Use the resultLauncher object to request location permission.
private final ActivityResultLauncher<String> resultLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
getCurrentLocation();
} else {
Toast.makeText(this, "Location permission not granted", Toast.LENGTH_SHORT).show();
}
});