All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gluonhq.charm.down.android.AndroidLocationService Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2015, Gluon
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *     * Neither the name of Gluon, any associated website, nor the
 * names of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL GLUON BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.gluonhq.charm.down.android;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import com.gluonhq.charm.down.common.PositionService;
import com.gluonhq.charm.down.common.Position;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafxports.android.FXActivity;

/**
 * An implementation of the
 * {@link com.gluonhq.charm.down.common.PositionService PositionService} for the
 * Android platform.
 */
class AndroidPositionService implements PositionService, LocationListener {

    private static final Logger LOG = Logger.getLogger(AndroidPositionService.class.getName());

    /**
     * The minimum number of milliseconds between location updates.
     */
    private static final long MIN_TIME = 5000;
    /**
     * The minimum number of meters between location updates.
     */
    private static final float MIN_DISTANCE = 15.0f;

    private final ObjectProperty positionProperty = new SimpleObjectProperty<>();

    private final LocationManager locationManager;
    private final String locationProvider;

    private AndroidLooperTask looperTask = null;

    public AndroidPositionService() {
        Context activityContext = FXActivity.getInstance();

        Object systemService = activityContext.getSystemService(FXActivity.LOCATION_SERVICE);
        locationManager = (LocationManager) systemService;

        List locationProviders = locationManager.getAllProviders();
        if (locationProviders == null || locationProviders.isEmpty()) {
            locationProvider = LocationManager.GPS_PROVIDER;
        } else {
            LOG.log(Level.INFO, String.format("Available location providers on this device: %s.", locationProviders.toString()));
            if (locationProviders.contains(LocationManager.GPS_PROVIDER)) {
                locationProvider = LocationManager.GPS_PROVIDER;
            } else if (locationProviders.contains(LocationManager.NETWORK_PROVIDER)) {
                locationProvider = LocationManager.NETWORK_PROVIDER;
            } else if (locationProviders.contains(LocationManager.PASSIVE_PROVIDER)) {
                locationProvider = LocationManager.PASSIVE_PROVIDER;
            } else {
                locationProvider = locationProviders.get(0);
            }
        }
        LOG.log(Level.INFO, String.format("Picked %s as location provider.", locationProvider));

        boolean locationProviderEnabled = locationManager.isProviderEnabled(locationProvider);
        if (!locationProviderEnabled) {
            LOG.log(Level.INFO, String.format("Location provider %s is not enabled, starting intent to ask user to activate the location provider.", locationProvider));
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            activityContext.startActivity(intent);
        }

        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        if (lastKnownLocation != null) {
            LOG.log(Level.INFO, String.format("Last known location for provider %s: %f / %f", locationProvider, lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()));

            Platform.runLater(() -> {
                Position lastKnownPosition = new Position(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                positionProperty.set(lastKnownPosition);
            });
        }

        createLooperTask();
    }

    @Override
    public ReadOnlyObjectProperty positionProperty() {
        return positionProperty;
    }

    @Override
    public Position getPosition() {
        return positionProperty.get();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            LOG.log(Level.INFO, String.format("Android location changed: %f / %f", location.getLatitude(), location.getLongitude()));

            Platform.runLater(() -> {
                Position newPosition = new Position(location.getLatitude(), location.getLongitude());
                positionProperty.set(newPosition);
            });
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        LOG.log(Level.INFO, String.format("Status for LocationProvider %s changed to %d.", provider, status));
    }

    @Override
    public void onProviderEnabled(String provider) {
        LOG.log(Level.INFO, String.format("LocationProvider %s was enabled by the user, starting looper task.", provider));

        if (provider.equals(locationProvider) && looperTask == null) {
            createLooperTask();
        }
    }

    private void createLooperTask() {
        LOG.log(Level.INFO, String.format("Creating LooperTask to request location updates every %d milliseconds or %f meters.", MIN_TIME, MIN_DISTANCE));

        looperTask = new AndroidLooperTask() {

            @Override
            public void execute() {
                locationManager.requestLocationUpdates(locationProvider, MIN_TIME, MIN_DISTANCE, AndroidPositionService.this);
            }
        };

        Thread thread = new Thread(looperTask);
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public void onProviderDisabled(String provider) {
        LOG.log(Level.INFO, String.format("LocationProvider %s was disabled by the user, quitting looper task.", provider));

        if (provider.equals(locationProvider) && looperTask != null) {
            looperTask.quit();
            looperTask = null;
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy