How to Get Current Location in Android?
Last Updated :
07 Apr, 2025
As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user's current location in Android. There are two ways to get the current location of any Android device:
- Android’s Location Manager API
- Fused Location Provider: Google Play Services Location APIs
Question: Which one is efficient and why?
Answer: Fused Location Provider because it optimizes the device’s use of battery power.
Before moving any of the above methods we will have to take location permission.
Step by Step Implementation
Step 1: Create a new project
To create a new project in the Android Studio, please refer to How to Create/Start a New Project in Android Studio?
Step 2: Adding permissions in manifest
Navigate to app > manifests > AndroidManifest.xml and add the following permissions under the <manifest/> tag.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
In order to receive location updates from NETWORK_PROVIDER or GPS_PROVIDER, you must request the user’s permission by declaring either the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission, respectively, in your Android manifest file. Without these permissions, your application will fail at runtime when requesting location updates.
If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. Permission for ACCESS_COARSE_LOCATION allows access only to NETWORK_PROVIDER.
Step 3: Working with activity_main.xml
Navigate to app > res > layout > activity_main.xml and add a textview to display location and a button to fetch the location.
activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="24dp"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/locationText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location will be shown here"
android:textSize="18sp"
android:textAlignment="center"
android:padding="16dp" />
<Button
android:id="@+id/getLocationBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Current Location" />
</LinearLayout>
Design UI:
Step 4: Working with MainActivity file
Navigate to app > java > {package-name} > MainActivity.java/.kt and add the following code.
MainActivity.java
package org.geeksforgeeks.demo;
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 androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
public class MainActivity extends AppCompatActivity {
// Declare variables
private FusedLocationProviderClient locationClient;
private TextView locationText;
private static final int LOCATION_PERMISSION_REQUEST = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize TextView and Button from layout
locationText = findViewById(R.id.locationText);
Button getLocationBtn = findViewById(R.id.getLocationBtn);
// Initialize the location provider client
locationClient = LocationServices.getFusedLocationProviderClient(this);
// Set a click listener for the button
getLocationBtn.setOnClickListener(v -> getCurrentLocation());
}
// Function to get the current location
private void getCurrentLocation() {
// Check if location permission is granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request permission if not granted
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST);
return;
}
// Fetch the last known location
locationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// Get latitude and longitude
double lat = location.getLatitude();
double lon = location.getLongitude();
// Display location in TextView
locationText.setText("Latitude: " + lat + "\nLongitude: " + lon);
} else {
// Display error message if location is null
locationText.setText("Unable to get location");
}
}
});
}
// Handle the result of the permission request
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// If permission is granted, fetch location
getCurrentLocation();
} else {
// If permission is denied, show message
locationText.setText("Location permission denied");
}
}
}
MainActivity.kt
package org.geeksforgeeks.demo
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
class MainActivity : AppCompatActivity() {
// Declare a variable for the FusedLocationProviderClient
private lateinit var locationClient: FusedLocationProviderClient
// Declare a TextView to display location data
private lateinit var locationText: TextView
// Define a constant for the location permission request code
private val LOCATION_PERMISSION_REQUEST = 1001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize the TextView and Button from the layout
locationText = findViewById(R.id.locationText)
val getLocationBtn = findViewById<Button>(R.id.getLocationBtn)
// Initialize the location provider client
locationClient = LocationServices.getFusedLocationProviderClient(this)
// Set a click listener for the button to get the current location
getLocationBtn.setOnClickListener {
getCurrentLocation()
}
}
// Function to get the current location
private fun getCurrentLocation() {
// Check if the location permission is granted
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// If permission is not granted, request it from the user
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST
)
return
}
// Fetch the last known location
locationClient.lastLocation.addOnSuccessListener { location ->
if (location != null) {
// If location is available, extract latitude and longitude
val lat = location.latitude
val lon = location.longitude
// Display location in the TextView
locationText.text = "Latitude: $lat\nLongitude: $lon"
} else {
// If location is null, display an error message
locationText.text = "Unable to get location"
}
}
}
// Handle the result of the permission request
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// Check if the permission was granted
if (requestCode == LOCATION_PERMISSION_REQUEST &&
grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
// If permission is granted, fetch the location
getCurrentLocation()
} else {
// If permission is denied, update the TextView with an error message
locationText.text = "Location permission denied"
}
}
}
Refer to the following github repo to get the entire code: Getting-Current-Location-Android
Output:
Similar Reads
How to Get Current Location Inside Android Fragment?
A Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
5 min read
How to get user location in Android
Many apps in Android uses user's locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user's latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query:
6 min read
How to Get Current Time and Date in Android?
Many times in android applications we have to capture the current date and time within our android application so that we can update our date according to that. In this article, we will take a look at How to get the current Time and Date in our android application. Note: This Android article covere
3 min read
How to Get Touch Coordinates of Screen in Android?
In Android, the app screen is a layout that can be used to display various UI elements like TextView, Button, ImageView, etc. These UI elements are positioned according to a set of pre-defined rules and developer changes. In simple words, each bit on any app screen defines a coordinate that can be u
3 min read
How to Listen to Orientation Change in Android?
In Android, applications can have orientations of types namely portrait and landscape. By default, every new project when created comes with a portrait orientation. However, this can be changed to landscape or semi. In the case of the semi, both portrait and landscape orientation is supported by the
3 min read
Using Fused Location API to Fetch Current Location in Android
Using Fused Location API to Retrieve Current Location Have you ever seen the movement of taxis on the roads while on their way to your location after booking an Uber cab? There are several apps that make use of some form of location service. The ability to use GPS to update the position is a pretty
7 min read
How to Calculate Distance Between two Locations in Android?
We have seen many apps that use Google Maps. These maps are used to indicate places on Google Maps and also we can use this to calculate the distance between two locations. In this article, we will take a look at calculating the distance between two locations in Android. What we are going to build
4 min read
How to Fetch Currently Running Tasks in Android Programmatically?
Android devices run several tasks in the background for providing a seamless experience to the users. Importantly, tracking background and foreground usages is important as it directly impacts the battery life and static memory, i.e. RAM. One can enable the developer option in the settings to track
2 min read
How to Use getCurrencyInstance Method in Android?
In Android, when we've to format the numbers of any TextView, we use "NumberFormat" class that is the base class of all formatting methods. So, different formatting methods are used for the different types of formatting. In this way, when we've to specify the numbers for a particular locale, getInst
3 min read
How to Implement Current Location Button Feature in Google Maps in Android?
The current location is a feature on Google Maps, that helps us locate the device's position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going t
5 min read