Reformatting and minor refactoring.

This commit is contained in:
Dmitry Yunitsky 2014-07-21 19:40:00 +03:00 committed by Alex Zolotarev
parent 3c7dfd7d2e
commit 5eb6b96636
3 changed files with 64 additions and 66 deletions

View file

@ -1,10 +1,5 @@
package com.mapswithme.maps.location;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.GeomagneticField;
@ -16,6 +11,7 @@ import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Display;
@ -33,18 +29,24 @@ import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.StubLogger;
import com.mapswithme.util.statistics.Statistics;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class LocationService implements
LocationListener, SensorEventListener, WifiLocation.Listener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
LocationListener, SensorEventListener, WifiLocationScanner.Listener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
{
private static final String TAG = LocationService.class.getName();
private final Logger mLogger = StubLogger.get();//SimpleLogger.get(this.toString());
private static final double DEFAULT_SPEED_MpS = 5;
private static final double DEFAULT_SPEED_MPS = 5;
private static final float DISTANCE_TO_RECREATE_MAGNETIC_FIELD_M = 1000;
private static final float MIN_SPEED_CALC_DIRECTION_MpS = 1;
private static final float MIN_SPEED_CALC_DIRECTION_MPS = 1;
private static final long LOCATION_EXPIRATION_TIME_MILLIS = 5 * 60 * 1000;
private static final String GS_LOCATION_PROVIDER = "fused";
@ -57,9 +59,11 @@ public class LocationService implements
public interface Listener
{
public void onLocationUpdated(final Location l);
public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy);
public void onLocationError(int errorCode);
};
}
private final HashSet<Listener> mObservers = new HashSet<Listener>(10);
@ -70,7 +74,7 @@ public class LocationService implements
/// Current heading if we are moving (-1.0 otherwise)
private double mDrivingHeading = -1.0;
private WifiLocation mWifiScanner = null;
private WifiLocationScanner mWifiScanner = null;
private final SensorManager mSensorManager;
private Sensor mAccelerometer = null;
@ -133,7 +137,7 @@ public class LocationService implements
private static boolean isNotExpired(Location l, long t)
{
long timeDiff;
if (Utils.apiEqualOrGreaterThan(17))
if (Utils.apiEqualOrGreaterThan(Build.VERSION_CODES.JELLY_BEAN_MR1))
timeDiff = (SystemClock.elapsedRealtimeNanos() - l.getElapsedRealtimeNanos()) / 1000000;
else
timeDiff = System.currentTimeMillis() - t;
@ -150,13 +154,13 @@ public class LocationService implements
private void startWifiLocationUpdate()
{
final boolean isWifiEnabled = ((WifiManager)mApplication.getSystemService(Context.WIFI_SERVICE)).isWifiEnabled();
final boolean isWifiEnabled = ((WifiManager) mApplication.getSystemService(Context.WIFI_SERVICE)).isWifiEnabled();
if (isWifiEnabled &&
Statistics.INSTANCE.isStatisticsEnabled(mApplication) &&
ConnectionState.isConnected(mApplication))
{
if (mWifiScanner == null)
mWifiScanner = new WifiLocation();
mWifiScanner = new WifiLocationScanner();
mLogger.d("Invoke WiFi scanner.");
mWifiScanner.startScan(mApplication, this);
@ -198,7 +202,7 @@ public class LocationService implements
private void calcDirection(Location l)
{
// Try to calculate direction if we are moving
if (l.getSpeed() >= MIN_SPEED_CALC_DIRECTION_MpS && l.hasBearing())
if (l.getSpeed() >= MIN_SPEED_CALC_DIRECTION_MPS && l.hasBearing())
mDrivingHeading = bearingToHeading(l.getBearing());
else
mDrivingHeading = -1.0;
@ -236,8 +240,8 @@ public class LocationService implements
if (mMagneticField == null ||
(mLastLocation == null || l.distanceTo(mLastLocation) > DISTANCE_TO_RECREATE_MAGNETIC_FIELD_M))
{
mMagneticField = new GeomagneticField( (float)l.getLatitude(), (float)l.getLongitude(),
(float)l.getAltitude(), l.getTime());
mMagneticField = new GeomagneticField((float) l.getLatitude(), (float) l.getLongitude(),
(float) l.getAltitude(), l.getTime());
}
}
@ -246,23 +250,24 @@ public class LocationService implements
}
private native float[] nativeUpdateCompassSensor(int ind, float[] arr);
private float[] updateCompassSensor(int ind, float[] arr)
{
/*
Log.d(TAG, "Sensor before, Java: " +
String.valueOf(arr[0]) + ", " +
String.valueOf(arr[1]) + ", " +
String.valueOf(arr[2]));
*/
// Log.d(TAG, "Sensor before, Java: " +
// String.valueOf(arr[0]) + ", " +
// String.valueOf(arr[1]) + ", " +
// String.valueOf(arr[2]));
final float[] ret = nativeUpdateCompassSensor(ind, arr);
/*
Log.d(TAG, "Sensor after, Java: " +
String.valueOf(ret[0]) + ", " +
String.valueOf(ret[1]) + ", " +
String.valueOf(ret[2]));
*/
// Log.d(TAG, "Sensor after, Java: " +
// String.valueOf(ret[0]) + ", " +
// String.valueOf(ret[1]) + ", " +
// String.valueOf(ret[2]));
return ret;
}
@ -366,7 +371,7 @@ public class LocationService implements
{
angle += correction;
final double twoPI = 2.0*Math.PI;
final double twoPI = 2.0 * Math.PI;
angle = angle % twoPI;
// normalize angle into [0, 2PI]
@ -433,6 +438,7 @@ public class LocationService implements
}
protected abstract void setUp();
protected abstract void startUpdates(Listener l);
protected void stopUpdates()
@ -457,7 +463,7 @@ public class LocationService implements
if (mLastLocation == null)
return true;
final double s = Math.max(DEFAULT_SPEED_MpS, (l.getSpeed() + mLastLocation.getSpeed()) / 2.0);
final double s = Math.max(DEFAULT_SPEED_MPS, (l.getSpeed() + mLastLocation.getSpeed()) / 2.0);
return (l.getAccuracy() < (mLastLocation.getAccuracy() + s * getLocationTimeDiffS(l)));
}
@ -471,7 +477,7 @@ public class LocationService implements
@SuppressLint("NewApi")
private double getLocationTimeDiffS(Location l)
{
if (Utils.apiEqualOrGreaterThan(17))
if (Utils.apiEqualOrGreaterThan(Build.VERSION_CODES.JELLY_BEAN_MR1))
return (l.getElapsedRealtimeNanos() - mLastLocation.getElapsedRealtimeNanos()) * 1.0E-9;
else
{

View file

@ -1,14 +1,4 @@
package com.mapswithme.maps.location;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
@ -19,24 +9,37 @@ import android.location.Location;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.SystemClock;
import com.mapswithme.util.Constants;
import com.mapswithme.util.Utils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.StubLogger;
import com.mapswithme.util.statistics.Statistics;
public class WifiLocation extends BroadcastReceiver
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class WifiLocationScanner extends BroadcastReceiver
{
private Logger mLogger = StubLogger.get();//SimpleLogger.get(this.toString());
private static final String MWM_GEOLOCATION_SERVER = "http://geolocation.server/";
/// Limit received WiFi accuracy with 20 meters.
private static final double MIN_PASSED_ACCURACY_M = 20;
public interface Listener
{
public void onWifiLocationUpdated(Location l);
public Location getLastGPSLocation();
}
@ -44,11 +47,6 @@ public class WifiLocation extends BroadcastReceiver
private WifiManager mWifi = null;
public WifiLocation()
{
//mLogger = new FileLogger("WiFiLocation", MWMApplication.get().getDataStoragePath());
}
/// @return true if was started successfully.
public boolean startScan(Context context, Listener l)
{
@ -84,12 +82,12 @@ public class WifiLocation extends BroadcastReceiver
}
@SuppressLint("NewApi")
private static void appendID(StringBuilder json)
private static void appendId(StringBuilder json)
{
json.append(",\"id\":{\"currentTime\":");
json.append(String.valueOf(System.currentTimeMillis()));
if (Utils.apiEqualOrGreaterThan(17))
if (Utils.apiEqualOrGreaterThan(Build.VERSION_CODES.JELLY_BEAN_MR1))
{
json.append(",\"elapsedRealtimeNanos\":");
json.append(String.valueOf(SystemClock.elapsedRealtimeNanos()));
@ -103,7 +101,7 @@ public class WifiLocation extends BroadcastReceiver
{
l.setTime(jID.getLong("currentTime"));
if (Utils.apiEqualOrGreaterThan(17))
if (Utils.apiEqualOrGreaterThan(Build.VERSION_CODES.JELLY_BEAN_MR1))
l.setElapsedRealtimeNanos(jID.getLong("elapsedRealtimeNanos"));
}
@ -116,7 +114,7 @@ public class WifiLocation extends BroadcastReceiver
// Prepare JSON request with BSSIDs
final StringBuilder json = new StringBuilder("{\"version\":\"2.0\"");
appendID(json);
appendId(json);
final boolean statsEnabled = Statistics.INSTANCE.isStatisticsEnabled(context);
@ -193,7 +191,6 @@ public class WifiLocation extends BroadcastReceiver
final String jsonString = json.toString();
// From Honeycomb, networking calls should be always executed at non-UI thread.
new AsyncTask<String, Void, Boolean>()
{
// Result for Listener
@ -217,12 +214,11 @@ public class WifiLocation extends BroadcastReceiver
try
{
final URL url = new URL(MWM_GEOLOCATION_SERVER);
final URL url = new URL(Constants.GEOLOCATION_SERVER_MAPSME);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
// Write JSON query
//mLogger.d("JSON request = ", jsonString);
mLogger.d("Post JSON request with length = ", jsonString.length());
conn.setDoOutput(true);
@ -239,8 +235,6 @@ public class WifiLocation extends BroadcastReceiver
while ((line = rd.readLine()) != null)
response += line;
//mLogger.d("JSON response = ", response);
final JSONObject jRoot = new JSONObject(response);
final JSONObject jLocation = jRoot.getJSONObject("location");
final double lat = jLocation.getDouble("latitude");
@ -254,16 +248,13 @@ public class WifiLocation extends BroadcastReceiver
setLocationCurrentTime(jRoot.getJSONObject("id"), mLocation);
return true;
}
catch (IOException e)
} catch (IOException e)
{
mLogger.d("Unable to get location from server: ", e);
}
catch (JSONException e)
} catch (JSONException e)
{
mLogger.d("Unable to parse JSON responce: ", e);
}
finally
} finally
{
if (conn != null)
conn.disconnect();

View file

@ -5,5 +5,6 @@ public class Constants
private Constants() {}
public static final String PLAY_MARKET_APP_PREFIX = "market://details?id=";
public static final String GEOLOCATION_SERVER_MAPSME = "http://geolocation.server/";
}