reading-notes-ma


Project maintained by mohnalkhateeb Hosted on GitHub Pages — Theme by mattgraham

Location

location

Get the last known location

Set up Google Play services

Specify app permissions

    <!-- Recommended for Android 9 (API level 28) and lower. -->
    <!-- Required for Android 10 (API level 29) and higher. -->
    <service
        android:name="MyNavigationService"
        android:foregroundServiceType="location" ... >
        <!-- Any inner elements would go here. -->
    </service>

    <manifest ... >
    <!-- Always include this permission -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <!-- Include only if your app benefits from precise location access. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    </manifest>

    <manifest ... >
    <!-- Required only when requesting background location access on
        Android 10 (API level 29) and higher. -->
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    </manifest>

Create location services client

    private FusedLocationProviderClient fusedLocationClient;

    // ..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }

Get the last known location

    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                    }
                }
            });