[JAVA] Erfassung von Standortinformationen mit FusedLocationProviderClient

Überblick

Früher wurde LocationManager häufig zum Abrufen von Standortinformationen in Android-Apps verwendet. GooglePlayServices ab Version 11.6.0 unterstützt jedoch den benutzerfreundlicheren und genaueren FusedLocationProviderClient.

Beispiel

Berechtigungseinstellungen

Wenn Sie Standortinformationen in Android-Apps verwenden möchten, müssen Sie Manifest Berechtigungen hinzufügen.

AndroidManifest.xml


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

Erstellen Sie eine Klasse zum Verwalten von Standortinformationen

Wenn Sie die Funktion zum Abrufen von Standortinformationen an mehreren Stellen in der App benötigen, können Sie bequem eine Allzweckklasse erstellen, damit diese von jedem Ort aus aufgerufen werden kann.

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() {
        //Berechtigungen überprüfen
        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;
        }
        
        //Wenn der Standortinformationsdienst des Terminals deaktiviert ist, zeigen Sie den Einstellungsbildschirm an und fordern Sie ihn auf, ihn zu aktivieren.
        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("Bitte aktivieren Sie den Standortinformationsdienst auf dem Einstellungsbildschirm")
                .setPositiveButton("Aufbau", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton("Stornieren", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //NOP
                    }
                })
                .create()
                .show();
    }
}

Übergeordnete Klasse definieren

Definieren Sie eine abstrakte Klasse, die MyLocationManager.OnLocationResultListener implementiert, damit Sie Standortinformationen mit mehreren Fragmenten abrufen können. Zu diesem Zeitpunkt übernimmt onResume / onPause den Start / Stopp der Positionsinformationserfassung, sodass die Positionsinformationen nur erfasst werden, wenn Fragment aktiv ist.

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();
        }
    }
}

Anwendungsbeispiel

Durch Erben des obigen BaseFragments in dem Fragment, das die Standortinformationen verwenden möchte, können Sie den Rückruf erhalten, wenn die Standortinformationserfassung in onLocationResult erfolgreich ist.

python


public class SomeFragment extends Fragment {
    ...

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

        //Holen Sie sich Breite / Länge
        double latitude = locationResult.getLastLocation().getLatitude();
        double longitude = locationResult.getLastLocation().getLongitude();
    }

    ...
}

Referenz

Recommended Posts

Erfassung von Standortinformationen mit FusedLocationProviderClient
Erfassung von Eingabeinhalten mit Scanner (Java)
Erhalten Sie schnell Standortinformationen
Beispiel für die Verwendung von vue.config.js
Zusammenfassung zur Informationssicherheit
Zusammenfassung der Verwendung von FragmentArgs
Zusammenfassung der Verwendung von DBFlow
Holen Sie sich Android-Standortinformationen
Beispiel für Parameter mit where
Zusammenfassung der Verwendung von ButterKnife
Beispiel für die Verwendung einer abstrakten Klasse
Ratenbegrenzung mit RateLimiter of Resilience4j
Löschen von Exif-Informationen mit Sanselan