Java how to get the current location in android

Java how to get the current location in android

To get the current location in an Android app, you can use the FusedLocationProviderClient class to request location updates from the device's location services. The FusedLocationProviderClient class provides methods to get the last known location and request location updates using the device's GPS, network, or passive location providers.

Here's an example of how you can get the current location in an Android app:

ref‮t re‬o:lautturi.com
import android.location.Location;
import android.util.Log;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

// ...

private FusedLocationProviderClient mFusedLocationClient;

// ...

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

mFusedLocationClient.getLastLocation()
    .addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null) {
                Log.d(TAG, "Latitude: " + location.getLatitude());
                Log.d(TAG, "Longitude: " + location.getLongitude());
            } else {
                Log.d(TAG, "Location not available");
            }
        }
    });

In this example, the mFusedLocationClient object is a FusedLocationProviderClient instance that provides access to the device's location services. The getLastLocation() method is used to get the last known location, and the OnSuccessListener is called when the location is available. The location object holds the current location, and the getLatitude() and getLongitude() methods are used to get the latitude and longitude coordinates.

To request location updates, you can use the requestLocationUpdates() method of the FusedLocationProviderClient class. This method takes a LocationRequest object that defines the parameters of the location update request, such as the update interval and the desired accuracy, and a LocationCallback object that is called when the location is updated.

Created Time:2017-11-03 23:27:09  Author:lautturi