[JAVA] Acquisition of location information using FusedLocationProviderClient

Overview

Previously, LocationManager was commonly used for Android apps to get location information, but Google Play Services version 11.6.0 and above supports the FusedLocationProviderClient, which is easier to use and more accurate.

example

Permission settings

If you want to use location information in Android app, you need to add permission to Manifest.

AndroidManifest.xml


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Create a class to manage location information

If you need the function to get location information in multiple places in the app, it is convenient to create a general-purpose class so that you can call it from any place.

MyLocationManager


import com.google.android.gms.location.*;

public class MyLocationManager extends LocationCallback {
    private static final int LOCATION_REQUEST_CODE = 1;
    private Context context;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private OnLocationResultListener mListener;

    public interface OnLocationResultListener {
        void onLocationResult(LocationResult locationResult);
    }

    public LocationManager(Context context, OnLocationResultListener mListener) {
        this.context = context;
        this.mListener = mListener;
        this.fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
    }

    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        mListener.onLocationResult(locationResult);
    }

    public void startLocationUpdates() {
        //Check permissions
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Logger.d("Permission required.");
            ActivityCompat.requestPermissions((Activity) context, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
            }, LOCATION_REQUEST_CODE);

            return;
        }
        
        //If the location information service of the terminal is disabled, display the setting screen and prompt to enable it.
        if (!isGPSEnabled()) {
            showLocationSettingDialog();
            return;
        }

        LocationRequest request = new LocationRequest();
        request.setInterval(5000);
        request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        fusedLocationProviderClient.requestLocationUpdates(request, this,null);
    }

    public void stopLocationUpdates() {
        fusedLocationProviderClient.removeLocationUpdates(this);
    }

    private Boolean isGPSEnabled() {
        android.location.LocationManager locationManager = (android.location.LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    private void showLocationSettingDialog() {
        new android.app.AlertDialog.Builder(context)
                .setMessage("Please enable location services on the settings screen")
                .setPositiveButton("Setting", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //NOP
                    }
                })
                .create()
                .show();
    }
}

Define parent class

Define an abstract class that implements MyLocationManager.OnLocationResultListener so that you can get location information with multiple Fragments. At that time, onResume / onPause handles the start / stop of location information acquisition so that location information is acquired only when Fragment is active.

BaseFragment


public abstract class BaseFragment extends Fragment 
         implements MyLocationManager.OnLocationResultListener {
    private MyLocationManager locationManager;

    @Override
    public void onResume() {
        super.onResume();

        locationManager = new MyLocationManager(getContext(), this);
        locationManager.startLocationUpdates();
    }

    @Override
    public void onPause() {
        super.onPause();

        if (locationManager != null) {
            locationManager.stopLocationUpdates();
        }
    }
}

Example of use

By inheriting the above BaseFragment in the Fragment that wants to use the location information, you can receive the callback when the location information acquisition is successful in onLocationResult.

python


public class SomeFragment extends Fragment {
    ...

    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult == null) {
            Logger.e("# No location data.");
            return;
        }

        //Get latitude / longitude
        double latitude = locationResult.getLastLocation().getLatitude();
        double longitude = locationResult.getLastLocation().getLongitude();
    }

    ...
}

reference

-Official: FusedLocationProviderClient -[Get location information with Fused Location on Google Play Service](https://blog.tkt989.info/2017/12/09/google-play-service%E3%81%AEfusedlocation%E3%81%A7%E4% BD% 8D% E7% BD% AE% E6% 83% 85% E5% A0% B1% E3% 82% 92% E5% 8F% 96% E5% BE% 97 /) -Get location information using FusedLocationProviderClient

Recommended Posts

Acquisition of location information using FusedLocationProviderClient
Acquisition of article information in ruby ​​scraping
Acquisition of input contents using Scanner (Java)
Get location information quickly
Example of using vue.config.js
Summary of information security
Summary of using FragmentArgs
Summary of using DBFlow
Get Android location information
Example of params using where
Summary of using Butter Knife
Example of using abstract class
Rate-Limiting using RateLimiter of Resilience4j
Deleting Exif information using sanselan