Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 15 Lab 15 – Display the Device's Current Location Coordinates

Week 15 – App Store Deployment and Mobile Programming Languages · 150 min read · 9 MCQs to check yourself

Android GPS tutorial with the Fused Location Provider

Location-aware apps: geolocation APIs and FusedLocationProviderClient

Objective

Ask for location permission at run time, get the device's current latitude and longitude with FusedLocationProviderClient, show the accuracy and the street address (reverse geocoding), and receive live updates that stop when the screen is hidden. CLOs: CLO-2 (develop location-aware apps), CLO-3 (battery vs accuracy trade-off), CLO-4 (use Google Play services).

What you will build in CampusMate

MyLocationActivity ("Where am I on campus?"):

Shows Example
Latitude, Longitude 33.684400, 73.047900
Accuracy ± 12 m
Address Street 5, Islamabad
Buttons Get my location, Live updates ON/OFF, Open in Maps (Lab 14)

Workflow

Step What you do File
1 Add the dependency and permissions build.gradle.kts, manifest
2 Layout activity_my_location.xml
3 Permission launcher (fine + coarse) MyLocationActivity.java
4 Get the current location fetchLocation()
5 Show coordinates and address showLocation()
6 Live updates and stopping them in onPause startUpdates() / onPause()
7 Test on the emulator Extended controls → Location

Step 1 – Dependency and permissions

build.gradle.kts (Module :app) → Sync:

implementation("com.google.android.gms:play-services-location:21.3.0")

Manifest, above <application>:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Permission Accuracy Source
ACCESS_FINE_LOCATION Precise – a few metres GPS
ACCESS_COARSE_LOCATION Approximate – about 1–3 km Wi-Fi / cell towers
From Android 12, an app that wants precise location must request both; the user may still choose "Approximate".

Step 2 – Layout (activity_my_location.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    android:padding="24dp">

    <TextView
        android:id="@+id/tvCoords"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lat: –   Lng: –"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvAccuracy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvAddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/btnGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Get my location" />

    <com.google.android.material.materialswitch.MaterialSwitch
        android:id="@+id/swLive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Live updates" />

    <Button android:id="@+id/btnOpenMap"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open in Maps" />
</LinearLayout>

Step 3 – Ask for permission at run time

package com.example.campusmate;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.*;
import com.google.android.material.materialswitch.MaterialSwitch;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;

public class MyLocationActivity extends AppCompatActivity {

    private FusedLocationProviderClient fused;
    private TextView tvCoords, tvAccuracy, tvAddress;
    private MaterialSwitch swLive;
    private Location last;                          // last known fix

    // Asks for BOTH permissions in one dialog
    private final ActivityResultLauncher<String[]> permissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
                if (result.containsValue(true)) fetchLocation();       // fine OR coarse granted
                else Toast.makeText(this, "Location permission denied", Toast.LENGTH_SHORT).show();
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_location);

        fused = LocationServices.getFusedLocationProviderClient(this);
        tvCoords = findViewById(R.id.tvCoords);
        tvAccuracy = findViewById(R.id.tvAccuracy);
        tvAddress = findViewById(R.id.tvAddress);
        swLive = findViewById(R.id.swLive);

        findViewById(R.id.btnGet).setOnClickListener(v -> checkPermissionAndFetch());
        swLive.setOnCheckedChangeListener((b, on) -> { if (on) startUpdates(); else stopUpdates(); });
        findViewById(R.id.btnOpenMap).setOnClickListener(v -> openInMaps());
    }

    private boolean hasPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED;
    }

    private void checkPermissionAndFetch() {
        if (hasPermission()) fetchLocation();
        else permissionLauncher.launch(new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION});
    }

    // Steps 4–6 below
}

Step 4 – Get the current location

@SuppressLint("MissingPermission")          // we checked the permission before calling
private void fetchLocation() {
    tvCoords.setText("Getting location…");
    fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null)   // fresh single fix (GPS)
            .addOnSuccessListener(location -> {
                if (location != null) showLocation(location);
                else tvCoords.setText("Location not available – turn on Location (GPS)");
            })
            .addOnFailureListener(e -> tvCoords.setText("Error: " + e.getMessage()));
}

"Fused" = Google Play services combines GPS, Wi-Fi, cell towers and sensors to give the best location for the least battery.

Priority Use
PRIORITY_HIGH_ACCURACY GPS – most accurate, more battery
PRIORITY_BALANCED_POWER_ACCURACY ~100 m, less battery
getLastLocation() returns a cached location quickly but it may be null or old.

Step 5 – Show coordinates, accuracy and address

private void showLocation(Location loc) {
    last = loc;
    tvCoords.setText(String.format(Locale.US, "Lat: %.6f   Lng: %.6f",
            loc.getLatitude(), loc.getLongitude()));
    tvAccuracy.setText("Accuracy: ± " + Math.round(loc.getAccuracy()) + " m");   // radius in metres

    // Reverse geocoding (coordinates → address) may be slow, so do it in the background
    Executors.newSingleThreadExecutor().execute(() -> {
        String text;
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> list = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
            text = (list != null && !list.isEmpty()) ? list.get(0).getAddressLine(0) : "Address not found";
        } catch (Exception e) {
            text = "Address not available (no internet?)";
        }
        String finalText = text;
        runOnUiThread(() -> tvAddress.setText(finalText));     // views only on the main thread
    });
}

private void openInMaps() {
    if (last == null) { Toast.makeText(this, "Get the location first", Toast.LENGTH_SHORT).show(); return; }
    Uri uri = Uri.parse("geo:" + last.getLatitude() + "," + last.getLongitude()
            + "?q=" + last.getLatitude() + "," + last.getLongitude() + "(I am here)");
    startActivity(new Intent(Intent.ACTION_VIEW, uri));
}

Step 6 – Live updates, and stop them in onPause

private final LocationCallback callback = new LocationCallback() {
    @Override
    public void onLocationResult(@NonNull LocationResult result) {
        Location loc = result.getLastLocation();
        if (loc != null) showLocation(loc);
    }
};

@SuppressLint("MissingPermission")
private void startUpdates() {
    if (!hasPermission()) { swLive.setChecked(false); checkPermissionAndFetch(); return; }
    LocationRequest request = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000) // every 5 s
            .build();
    fused.requestLocationUpdates(request, callback, Looper.getMainLooper());
}

private void stopUpdates() {
    fused.removeLocationUpdates(callback);
}

@Override
protected void onPause() {
    super.onPause();
    stopUpdates();                 // save battery when the screen is not visible
    swLive.setChecked(false);
}

Step 7 – Testing

Emulator: click ⋯ (Extended controls) → Location → enter 33.6844, 73.0479 → Set location, then tap Get my location. (If it returns null, open Google Maps once in the emulator.) Real phone: turn on Location; compare accuracy indoors and outdoors.

Test Expected result
First tap Dialog: Precise / Approximate and While using the app / Only this time / Don't allow
Allow precise Coordinates, accuracy of a few metres, address
Allow approximate Accuracy about 1–3 km
Don't allow Toast "Location permission denied"
Live updates ON + change emulator location Values change
Press Home Updates stop (switch OFF)
Open in Maps Google Maps pin "I am here"

Common errors and fixes

Problem Fix
Always "Location not available" Turn on device Location; set a location in Extended controls
SecurityException Permission not granted – call checkPermissionAndFetch() first
Red LocationServices Dependency missing – add play-services-location and Sync
Battery drains Remove updates in onPause()

Short and long questions

1. (Viva) Differentiate between ACCESSFINELOCATION and ACCESSCOARSELOCATION.

Model answer

FINE gives precise location (GPS, a few metres); COARSE gives approximate location (about 1–3 km). Both are dangerous runtime permissions; since Android 12 apps request both and the user may grant only approximate.

2. (Viva) Explain how your app obtained the current location.

Model answer

It checked/requested location permissions, confirmed location services were enabled, created a FusedLocationProviderClient with LocationServices.getFusedLocationProviderClient(this) and called getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, token); in the success listener it displayed latitude, longitude and accuracy.

3. (Viva) How did you receive continuous location updates and why must they be stopped?

Model answer

A LocationRequest (high accuracy, every 5 s) was passed to fused.requestLocationUpdates with a LocationCallback whose onLocationResult updated the UI. Updates are removed in onPause because GPS keeps the radio active and drains the battery.

This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 15 Theory – Deployment on App Stores; Mobile Programming Languages · Next: Week 16 Theory – Challenges with Mobility and Wireless Communication; Location-Aware Applications

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester