Published on

Using Android Location Services

Authors
  • avatar
    Name
    how-to.digital
    Twitter

Using Android Location Services

Android provides a comprehensive set of location services that allow you to integrate location-based features into your applications. With Android Location Services, you can access various sources of location data, such as GPS, network triangulation, and sensor data, to determine the user's current location and track their movement. In this tutorial, we will explore how to use Android Location Services in your application.

Prerequisites

To follow along with this tutorial, you will need:

  • Android Studio IDE installed
  • Basic knowledge of Android development and Java programming language

Setting Up the Project

Let's begin by creating a new Android project in Android Studio:

  1. Open Android Studio and select "Start a new Android Studio project" from the welcome screen.
  2. Configure your project settings such as project name, package name, and location on your machine.
  3. Select "Empty Activity" as the project template.
  4. Set the activity name and layout name as per your preference.
  5. Click on "Finish" to create the project.

Configuring Permissions

To access the user's location, you need to declare the necessary permissions in the Android manifest file:

  1. Open the AndroidManifest.xml file in your project.
  2. Scroll to the <manifest> element and add the following permissions inside the <manifest> element:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The ACCESS_FINE_LOCATION permission allows the app to access precise location information, while ACCESS_COARSE_LOCATION allows access to approximate location information.

Implementing Location Services

Now let's implement the necessary code to use Android Location Services:

  1. Open the activity class file (MainActivity.java by default).
  2. Import the required classes:
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
  1. Set up constants for requesting location updates:
private static final int PERMISSION_REQUEST_CODE = 101;
private static final long UPDATE_INTERVAL = 5000; // 5 seconds
private static final long FASTEST_INTERVAL = 2000; // 2 seconds
  1. Inside your activity class, declare the following variables:
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
  1. Add the following code snippet inside your activity's onCreate() method to initialize the location services:
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult == null) {
            return;
        }

        for (Location location : locationResult.getLocations()) {
            // Handle location updates
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            // Add your logic here
        }
    }
};
  1. Add the following checkPermission() method to check and request necessary location permissions:
private void checkPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
    } else {
        startLocationUpdates();
    }
}
  1. Override the onRequestPermissionsResult() method to handle the permission request result:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (grantResults.length > 0 && grantResults[0] ==
                PackageManager.PERMISSION_GRANTED) {
            startLocationUpdates();
        } else {
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
    }
}
  1. Add the startLocationUpdates() method to begin receiving location updates:
private void startLocationUpdates() {
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
  1. Override the onStop() method to stop location updates when the activity is no longer visible:
@Override
protected void onStop() {
    super.onStop();
    if (fusedLocationProviderClient != null) {
        fusedLocationProviderClient.removeLocationUpdates(locationCallback);
    }
}
  1. Finally, call the checkPermission() method inside your onCreate() method to check for permissions and start location updates:
checkPermission();

Testing the Application

Build and run the application on an Android device or emulator. You will be prompted to grant location permissions to the application. Once you grant permission, the app will start receiving location updates at regular intervals specified in the UPDATE_INTERVAL and FASTEST_INTERVAL.

You can add further logic inside the onLocationResult() method to process the location updates according to your application requirements.

Conclusion

In this tutorial, we learned how to use Android Location Services to access the user's location in an Android application. We covered the necessary permissions, setting up the project, implementing the location services, and handling location updates. You can now integrate location-based features seamlessly into your Android applications.