Java tutorial
/* Copyright 2016 Alan Sparrow This file is part of Wifefinder. Wifefind is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. */ package uk.org.freeflight.wifefinder; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.content.ContextCompat; class WifeFinderLocationService implements LocationListener { private Context context; private Location location; private LocationManager locationManager; private boolean running; WifeFinderLocationService(Context c) { context = c; location = new Location("WF"); locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); running = false; } void start() { location.removeAccuracy(); if (checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); running = true; } if (checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)) { if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); running = true; } } } void stop() { try { locationManager.removeUpdates(this); running = false; } catch (SecurityException ignored) { } } boolean isRunning() { return running; } double getLatitude() { return location.getLatitude(); } double getLongitude() { return location.getLongitude(); } void setLatitude(double latitude) { location.setLatitude(latitude); } void setLongitude(double longitude) { location.setLongitude(longitude); } double getAccuracy() { if (location.hasAccuracy()) { return location.getAccuracy(); } else { return 0; } } boolean hasAccuracy() { return location.hasAccuracy(); } double distanceTo(Location loc) { return location.distanceTo(loc); } double bearingTo(Location loc) { return location.bearingTo(loc); } boolean checkPermission(String permission) { return (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED); } @Override public void onLocationChanged(Location newLocation) { if (!location.hasAccuracy() || (newLocation.getAccuracy() < location.getAccuracy())) { location = newLocation; } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }