Merge branch 'master' of nes.uni-due.de:lbs/maptology
lbs-gitea/maptology/master There was a failure building this commit
lbs-gitea/maptology/master There was a failure building this commit
This commit is contained in:
@@ -11,6 +11,9 @@
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
|
||||
|
||||
<!-- required for notification with LED lights, this is idiotic -->
|
||||
<uses-permission android:name="android.permission.VIBRATE"/>
|
||||
@@ -62,15 +65,6 @@
|
||||
<action android:name="com.maptology.android.app.notice.SYNC"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<service android:name=".util.MaptologyService"/>
|
||||
<receiver
|
||||
android:name=".util.MaptologyService$AlarmReceiver"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED"/>
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<service android:name=".location.LocationService"/>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -30,7 +30,7 @@ import com.maptology.android.app.fragment.SettingsFragment;
|
||||
import com.maptology.android.app.fragment.ShareFragment;
|
||||
import com.maptology.android.app.util.CustomArrayAdapter;
|
||||
import com.maptology.android.app.util.MaptologyApp;
|
||||
import com.maptology.android.app.util.MaptologyService;
|
||||
import com.maptology.android.app.location.LocationService;
|
||||
import com.maptology.android.app.util.NavigationDataModel;
|
||||
import com.maptology.android.feign.api.DefaultApi;
|
||||
import com.maptology.android.feign.model.DeviceHandle;
|
||||
@@ -79,13 +79,12 @@ public class MainActivity extends AppCompatActivity {
|
||||
private String idString = null;
|
||||
private boolean result;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
/* Start the Service */
|
||||
MaptologyService.runService(this);
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setTitle(R.string.application_short);
|
||||
LocationService.runService(this);
|
||||
|
||||
setTitle(R.string.application_short);
|
||||
|
||||
checkPermissions();
|
||||
|
||||
|
||||
@@ -17,13 +17,13 @@ import com.locoslab.capi.android.leafless.icon.IconOptions;
|
||||
import com.locoslab.capi.android.leafless.marker.Marker;
|
||||
import com.locoslab.capi.android.leafless.marker.MarkerOptions;
|
||||
import com.maptology.android.app.R;
|
||||
import com.locoslab.api.data.maps.model.Coordinate;
|
||||
import com.locoslab.capi.android.leafless.*;
|
||||
import com.locoslab.capi.android.leafless.tile.TileLayer;
|
||||
import com.locoslab.capi.android.leafless.tile.TileLayerOptions;
|
||||
import com.maptology.android.app.repository.IValueListener;
|
||||
import com.maptology.android.app.repository.Value;
|
||||
import com.maptology.android.feign.api.DefaultApi;
|
||||
import com.maptology.android.feign.model.Coordinate;
|
||||
import com.maptology.android.feign.model.ShareInfo;
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ public class MapFragment extends AbstractFragment {
|
||||
/**
|
||||
* The center.
|
||||
*/
|
||||
private Coordinate center;
|
||||
private com.locoslab.api.data.maps.model.Coordinate center;
|
||||
|
||||
/**
|
||||
* The zoom level.
|
||||
@@ -101,12 +101,10 @@ public class MapFragment extends AbstractFragment {
|
||||
|
||||
|
||||
|
||||
private IValueListener<Location> locationListener = new IValueListener<Location>() {
|
||||
private IValueListener<Coordinate> locationListener = new IValueListener<Coordinate>() {
|
||||
@Override
|
||||
public void onValueChanged(Value<Location> source, Location oldValue, Location newValue) {
|
||||
public void onValueChanged(Value<Coordinate> source, Coordinate oldValue, Coordinate newValue) {
|
||||
if (newValue != null) {
|
||||
lastKnownLong=newValue.getLongitude();
|
||||
lastKnownLat=newValue.getLatitude();
|
||||
updateLocation(newValue.getLongitude(), newValue.getLatitude());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
/**
|
||||
* The location database to store location updates, computed positions
|
||||
* and associated wifi networks.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationContract {
|
||||
|
||||
/**
|
||||
* The table to store the released locations when they
|
||||
* are captured. This table is required to handle
|
||||
* transient network failsures.
|
||||
*/
|
||||
public class Update {
|
||||
/**
|
||||
* The name of the table.
|
||||
*/
|
||||
public static final String TABLE = "location_update";
|
||||
/**
|
||||
* The id of the row.
|
||||
*/
|
||||
public static final String ID = "_id";
|
||||
/**
|
||||
* The mandatory latitude of the location.
|
||||
*/
|
||||
public static final String LATITUDE = "latitude";
|
||||
/**
|
||||
* The mandatory longitude of the location.
|
||||
*/
|
||||
public static final String LONGITUDE = "longitude";
|
||||
/**
|
||||
* The optional altitude of the location.
|
||||
*/
|
||||
public static final String ALTITUDE = "altitude";
|
||||
/**
|
||||
* The optional precision of the location.
|
||||
*/
|
||||
public static final String PRECISION = "precision";
|
||||
/**
|
||||
* The optional speed of the location.
|
||||
*/
|
||||
public static final String SPEED = "speed";
|
||||
/**
|
||||
* The optional bearing of the location.
|
||||
*/
|
||||
public static final String BEARING = "bearing";
|
||||
/**
|
||||
* The mandatory timestamp of the location.
|
||||
*/
|
||||
public static final String TIMESTAMP = "timestamp";
|
||||
/**
|
||||
* The mandatory availability of the location.
|
||||
*/
|
||||
public static final String AVAILABILITY = "availability";
|
||||
/**
|
||||
* A mandatory flag to determine whether the location should be analyzed.
|
||||
*/
|
||||
public static final String ANALYZABLE = "analyzable";
|
||||
/**
|
||||
* A mandatory flag to denote whether the location can be stored.
|
||||
*/
|
||||
public static final String SHARABLE = "sharable";
|
||||
/**
|
||||
* The mandatory location provider that captured the location.
|
||||
*/
|
||||
public static final String PROVIDER = "provider";
|
||||
/**
|
||||
* The mandatory application version.
|
||||
*/
|
||||
public static final String VERSION = "version";
|
||||
}
|
||||
|
||||
/**
|
||||
* The table to store locations with their associated
|
||||
* networks so that we do not have to compute them
|
||||
* all the time.
|
||||
*/
|
||||
public class Position {
|
||||
|
||||
/**
|
||||
* The name of the table.
|
||||
*/
|
||||
public static final String TABLE = "location_position";
|
||||
/**
|
||||
* The id of rows.
|
||||
*/
|
||||
public static final String ID = "_id";
|
||||
/**
|
||||
* The mandatory latitude.
|
||||
*/
|
||||
public static final String LATITUDE = "latitude";
|
||||
/**
|
||||
* The mandatory longitude.
|
||||
*/
|
||||
public static final String LONGITUDE = "longitude";
|
||||
/**
|
||||
* The optional altitude.
|
||||
*/
|
||||
public static final String ALTITUDE = "altitude";
|
||||
/**
|
||||
* The optional precision.
|
||||
*/
|
||||
public static final String PRECISION = "precision";
|
||||
/**
|
||||
* The mandatory provider.
|
||||
*/
|
||||
public static final String PROVIDER = "provider";
|
||||
/**
|
||||
* The inital creation time of the location.
|
||||
*/
|
||||
public static final String CREATION_TIME = "creationTime";
|
||||
/**
|
||||
* The last usage time of the location.
|
||||
*/
|
||||
public static final String USAGE_TIME = "usageTime";
|
||||
}
|
||||
|
||||
/**
|
||||
* This table associates wifi networks with locations
|
||||
* such that we can search for locations by a set of
|
||||
* wifi networks.
|
||||
*/
|
||||
public class Network {
|
||||
|
||||
/**
|
||||
* Th name of the table.
|
||||
*/
|
||||
public static final String TABLE = "location_network";
|
||||
/**
|
||||
* The row id.
|
||||
*/
|
||||
public static final String ID = "_id";
|
||||
/**
|
||||
* The mandatory referenced location.
|
||||
*/
|
||||
public static final String POSITION = "position";
|
||||
/**
|
||||
* The bssid of the network.
|
||||
*/
|
||||
public static final String BSSID = "bssid";
|
||||
/**
|
||||
* The rssi value of the network.
|
||||
*/
|
||||
public static final String RSSI = "rssi";
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The db schema version.
|
||||
*/
|
||||
public static int VERSION = 1;
|
||||
|
||||
/**
|
||||
* The name of the database.
|
||||
*/
|
||||
public static final String DATABASE = "location.db";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
import android.content.Context;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteOpenHelper;
|
||||
import com.maptology.android.app.notice.NoticeContract;
|
||||
|
||||
/**
|
||||
* Implements an sqlite open helper for the the location db.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationHelper extends SQLiteOpenHelper {
|
||||
|
||||
/**
|
||||
* Creates the network table.
|
||||
*/
|
||||
private static String SQL_CREATE_NETWORK = "CREATE TABLE " + LocationContract.Network.TABLE + " ( "
|
||||
+ LocationContract.Network.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
+ LocationContract.Network.BSSID + " TEXT NOT NULL, "
|
||||
+ LocationContract.Network.RSSI + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Network.POSITION + " INTEGER NOT NULL "
|
||||
+ "REFERENCES " + LocationContract.Position.TABLE + " ( " +LocationContract.Position.ID + " ) ON DELETE CASCADE"
|
||||
+ " )";
|
||||
|
||||
/**
|
||||
* Deletes the network table.
|
||||
*/
|
||||
private static String SQL_DROP_NETWORK = "DROP TABLE IF EXISTS " + LocationContract.Network.TABLE;
|
||||
|
||||
/**
|
||||
* Creates an index on the bssid of the network table.
|
||||
*/
|
||||
private static String SQL_INDEX_NETWORK_BS = "CREATE INDEX " + LocationContract.Network.TABLE + "_BS "
|
||||
+ "ON " + LocationContract.Network.TABLE + " ( " + LocationContract.Network.BSSID + " )";
|
||||
|
||||
/**
|
||||
* Deletes the index on the expiration time.
|
||||
*/
|
||||
private static String SQL_DROP_NETWORK_BS = "DROP INDEX IF EXISTS " + LocationContract.Network.TABLE + "_BS";
|
||||
|
||||
|
||||
/**
|
||||
* Creates the table for the positions.
|
||||
*/
|
||||
private static String SQL_CREATE_POSITION = "CREATE TABLE " + LocationContract.Position.TABLE + " ( "
|
||||
+ LocationContract.Position.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
+ LocationContract.Position.LATITUDE + " REAL NOT NULL, "
|
||||
+ LocationContract.Position.LONGITUDE + " REAL NOT NULL, "
|
||||
+ LocationContract.Position.ALTITUDE + " REAL, "
|
||||
+ LocationContract.Position.PRECISION + " REAL, "
|
||||
+ LocationContract.Position.PROVIDER + " TEXT NOT NULL, "
|
||||
+ LocationContract.Position.CREATION_TIME + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Position.USAGE_TIME + " INTEGER NOT NULL "
|
||||
+ " )";
|
||||
|
||||
/**
|
||||
* Deletes the position table.
|
||||
*/
|
||||
private static String SQL_DROP_POSITION = "DROP TABLE IF EXISTS " + LocationContract.Position.TABLE;
|
||||
|
||||
/**
|
||||
* Creates an index over the usage time to quickly drop old stuff.
|
||||
*/
|
||||
private static String SQL_INDEX_POSITION_UT = "CREATE INDEX " + LocationContract.Position.TABLE + "_UT "
|
||||
+ "ON " + LocationContract.Position.TABLE + " ( " +LocationContract.Position.USAGE_TIME +" )";
|
||||
|
||||
/**
|
||||
* Drops the index on the usage time.
|
||||
*/
|
||||
private static String SQL_DROP_POSITION_UT = "DROP INDEX IF EXISTS " + LocationContract.Position.TABLE + "_UT";
|
||||
|
||||
/**
|
||||
* Creates a table to store the locations.
|
||||
*/
|
||||
private static String SQL_CREATE_UPDATE = "CREATE TABLE " + LocationContract.Update.TABLE + " ( "
|
||||
+ LocationContract.Update.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
+ LocationContract.Update.LATITUDE + " REAL, "
|
||||
+ LocationContract.Update.LONGITUDE + " REAL, "
|
||||
+ LocationContract.Update.ALTITUDE + " REAL, "
|
||||
+ LocationContract.Update.PRECISION + " REAL, "
|
||||
+ LocationContract.Update.SPEED + " REAL, "
|
||||
+ LocationContract.Update.BEARING + " REAL, "
|
||||
+ LocationContract.Update.VERSION + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Update.SHARABLE + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Update.ANALYZABLE + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Update.AVAILABILITY + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Update.TIMESTAMP + " INTEGER NOT NULL, "
|
||||
+ LocationContract.Update.PROVIDER + " TEXT "
|
||||
+ " )";
|
||||
|
||||
/**
|
||||
* Drops the location table.
|
||||
*/
|
||||
private static String SQL_DROP_UPDATE = "DROP TABLE IF EXISTS " + LocationContract.Update.TABLE;
|
||||
|
||||
/**
|
||||
* Creates a new helper from the context.
|
||||
*
|
||||
* @param context The context of the app.
|
||||
*/
|
||||
public LocationHelper(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a notice helper with the context and cursor factory.
|
||||
*
|
||||
* @param context The context.
|
||||
* @param factory The cursor factory.
|
||||
*/
|
||||
public LocationHelper(Context context, SQLiteDatabase.CursorFactory factory) {
|
||||
super(context, NoticeContract.DATABASE, factory, NoticeContract.VERSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the database and indexes.
|
||||
*
|
||||
* @param db The database.
|
||||
*/
|
||||
@Override
|
||||
public void onCreate(SQLiteDatabase db) {
|
||||
db.beginTransaction();
|
||||
try {
|
||||
// create tables
|
||||
db.execSQL(SQL_CREATE_UPDATE);
|
||||
db.execSQL(SQL_CREATE_POSITION);
|
||||
db.execSQL(SQL_CREATE_NETWORK);
|
||||
// create indexes
|
||||
db.execSQL(SQL_INDEX_POSITION_UT);
|
||||
db.execSQL(SQL_INDEX_NETWORK_BS);
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executed when the version number is incremented in the contract.
|
||||
* This implementation simply wipes the complete db.
|
||||
*
|
||||
* @param db The database.
|
||||
* @param oldVersion The old version.
|
||||
* @param newVersion The new version.
|
||||
*/
|
||||
@Override
|
||||
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
|
||||
// a quite crude "upgrade" script
|
||||
db.beginTransaction();
|
||||
try {
|
||||
// drop indexes
|
||||
db.execSQL(SQL_DROP_NETWORK_BS);
|
||||
db.execSQL(SQL_DROP_POSITION_UT);
|
||||
// drop tables
|
||||
db.execSQL(SQL_DROP_NETWORK);
|
||||
db.execSQL(SQL_DROP_POSITION);
|
||||
db.execSQL(SQL_DROP_UPDATE);
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
}
|
||||
// recreate everything
|
||||
onCreate(db);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,675 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.location.Location;
|
||||
import android.location.LocationListener;
|
||||
import android.location.LocationManager;
|
||||
import android.net.wifi.ScanResult;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.IBinder;
|
||||
import android.os.PowerManager;
|
||||
import android.os.SystemClock;
|
||||
import android.support.v4.content.ContextCompat;
|
||||
import android.util.Log;
|
||||
import com.maptology.android.app.util.MaptologyApp;
|
||||
import com.maptology.android.feign.model.Coordinate;
|
||||
import com.maptology.android.feign.model.DeviceHandle;
|
||||
import com.maptology.android.feign.model.ReleasedLocation;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A service to perform background localization.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationService extends Service {
|
||||
|
||||
/**
|
||||
* The code for the alarm.
|
||||
*/
|
||||
private static final int ALARM_CODE = 3321;
|
||||
|
||||
/**
|
||||
* A boolean extra to indicate whether the call is
|
||||
* coming from the alarm manager.
|
||||
*/
|
||||
private static final String EXTRA_ALARM = "alarm";
|
||||
|
||||
/**
|
||||
* The minimum time between two localization attempts.
|
||||
*/
|
||||
private static final long LOCALIZATION_TIMEOUT = 60000;
|
||||
|
||||
/**
|
||||
* The time to wait for wifi scans.
|
||||
*/
|
||||
private static final long WIFI_TIMEOUT = 20000;
|
||||
|
||||
/**
|
||||
* The time to wait for network locations.
|
||||
*/
|
||||
private static final long NETWORK_TIMEOUT = 30000;
|
||||
|
||||
/**
|
||||
* The time to wait for gps locations.
|
||||
*/
|
||||
private static final long GPS_TIMEOUT = 60000;
|
||||
|
||||
/**
|
||||
* The minimum number of networks to use a chached location
|
||||
* or to use the network location provider.
|
||||
*/
|
||||
private static final int NETWORK_MINIMUM = 4;
|
||||
|
||||
/**
|
||||
* The log tag to produce debug output.
|
||||
*/
|
||||
private static final String TAG = "LocationService";
|
||||
|
||||
/**
|
||||
* The application.
|
||||
*/
|
||||
private MaptologyApp app;
|
||||
|
||||
/**
|
||||
* The location manager to capture locations.
|
||||
*/
|
||||
private LocationManager locationManager;
|
||||
/**
|
||||
* The wifi manager to perform wifi scans and request wifi locks.
|
||||
*/
|
||||
private WifiManager wifiManager;
|
||||
/**
|
||||
* The power manager to request cpu locks.
|
||||
*/
|
||||
private PowerManager powerManager;
|
||||
|
||||
/**
|
||||
* The handler to process timeouts in the ui thread.
|
||||
*/
|
||||
private Handler handler;
|
||||
|
||||
/**
|
||||
* The current state of the service.
|
||||
*/
|
||||
private LocationState currentState = LocationState.IDLE;
|
||||
|
||||
/**
|
||||
* The current list of networks.
|
||||
*/
|
||||
private List<Network> currentNetworks = null;
|
||||
|
||||
/**
|
||||
* The time of the last localization attempt of the service.
|
||||
*/
|
||||
private long localizationTime = 0;
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A location listener that simply forwards its locations to
|
||||
* the service.
|
||||
*/
|
||||
private LocationListener locationListener = new LocationListener() {
|
||||
@Override
|
||||
public void onLocationChanged(Location location) {
|
||||
setLocation(location);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStatusChanged(String provider, int status, Bundle extras) { }
|
||||
|
||||
@Override
|
||||
public void onProviderEnabled(String provider) { }
|
||||
|
||||
@Override
|
||||
public void onProviderDisabled(String provider) { }
|
||||
};
|
||||
|
||||
/**
|
||||
* A wifi listener that receives scan results.
|
||||
*/
|
||||
private BroadcastReceiver wifiListener = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent != null && WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
|
||||
setScan(wifiManager.getScanResults());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The timeout listener, if set or null.
|
||||
*/
|
||||
private Runnable timeoutListener = null;
|
||||
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
// do not support binding
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
handler = new Handler();
|
||||
app = (MaptologyApp)getApplicationContext();
|
||||
locationManager = (LocationManager)app.getSystemService(LOCATION_SERVICE);
|
||||
wifiManager = (WifiManager)app.getSystemService(WIFI_SERVICE);
|
||||
powerManager = (PowerManager)app.getSystemService(POWER_SERVICE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
if (!isPeriodicExecution(intent)) {
|
||||
scheduleExecution(this);
|
||||
}
|
||||
// ensure that localization is only running, if it is not
|
||||
// running already or has been run only seconds ago
|
||||
long now = System.currentTimeMillis();
|
||||
if (currentState == LocationState.IDLE) {
|
||||
if (now - localizationTime > LOCALIZATION_TIMEOUT) {
|
||||
Log.d(TAG, "Starting localization state machine.");
|
||||
changeState();
|
||||
} else {
|
||||
Log.d(TAG, "Ignoring start request while timeout has not expired.");
|
||||
}
|
||||
} else {
|
||||
Log.d(TAG, "Ignoring start request while service is " + currentState + ".");
|
||||
}
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Triggers a state change to the next logical state of the state machine.
|
||||
*/
|
||||
private void changeState() {
|
||||
switch (currentState) {
|
||||
case IDLE: {
|
||||
// if we have wifi, perform scan to
|
||||
// determine whether we can use from cache,
|
||||
// or whether we use gps or network
|
||||
// otherwise prefer gps over net
|
||||
if (canUseWifi()) {
|
||||
startWifi();
|
||||
} else if (canUseGps()){
|
||||
startGps();
|
||||
} else if (canUseNetwork()){
|
||||
startNet();
|
||||
} else {
|
||||
resetState(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case WIFI: {
|
||||
// for minimum networks, attempt to get from cache
|
||||
// othewise use gps and then network or fail
|
||||
cleanupWifi();
|
||||
if (hasMinimumNetworks()) {
|
||||
startCache();
|
||||
} else if (canUseGps()) {
|
||||
startGps();
|
||||
} else if (canUseNetwork()) {
|
||||
startNet();
|
||||
} else {
|
||||
resetState(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case CACHE: {
|
||||
// if cache retrieval failed, try to use network
|
||||
// and then gps (we have enough networks) or fail
|
||||
if (canUseNetwork()) {
|
||||
startNet();
|
||||
} else if (canUseGps()) {
|
||||
startGps();
|
||||
} else {
|
||||
resetState(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case NET: {
|
||||
// if network fails, try to use gps instead or fail
|
||||
cleanupNet();
|
||||
if (canUseGps()) {
|
||||
startGps();
|
||||
} else {
|
||||
resetState(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GPS:{
|
||||
// if gps fails eventually, fail the process
|
||||
cleanupGps();
|
||||
resetState(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the state of the state machine and generates the
|
||||
* "unable" location update, if the location cannot be computed.
|
||||
* For both cases, an upload is triggered, if it is not running
|
||||
* already.
|
||||
*
|
||||
* @param success True to indicate success, false to indicate
|
||||
* an unrecovable failure.
|
||||
*/
|
||||
private void resetState(boolean success) {
|
||||
long now = System.currentTimeMillis();
|
||||
currentState = LocationState.IDLE;
|
||||
currentNetworks = null;
|
||||
localizationTime = now;
|
||||
// create an "unable" location, if this is not a success
|
||||
if (!success) {
|
||||
ReleasedLocation location = createLocation();
|
||||
location.setAvailability(ReleasedLocation.AvailabilityEnum.UNABLE);
|
||||
location.setTimestamp(now);
|
||||
app.getLocationStore().addUpdate(location);
|
||||
}
|
||||
// upload the location, if the upload is not yet running
|
||||
if (! app.getRepository().uploadingLocations.getValue()) {
|
||||
LocationUploadTask task = new LocationUploadTask(app);
|
||||
task.execute();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts localization using the gps provider.
|
||||
*/
|
||||
private void startGps() {
|
||||
Log.d(TAG, "Starting gps localization.");
|
||||
currentState = LocationState.GPS;
|
||||
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
|
||||
timeoutListener = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "Aborting gps localization.");
|
||||
changeState();
|
||||
}
|
||||
};
|
||||
handler.postDelayed(timeoutListener, GPS_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts localization using the network provider.
|
||||
*/
|
||||
private void startNet() {
|
||||
Log.d(TAG, "Starting network localization.");
|
||||
currentState = LocationState.NET;
|
||||
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
|
||||
timeoutListener = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "Aborting network localization.");
|
||||
changeState();
|
||||
}
|
||||
};
|
||||
handler.postDelayed(timeoutListener, NETWORK_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a wifi scan.
|
||||
*/
|
||||
private void startWifi() {
|
||||
Log.d(TAG, "Starting wifi scan.");
|
||||
currentState = LocationState.WIFI;
|
||||
registerReceiver(wifiListener, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
|
||||
timeoutListener = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "Aborting wifi scan.");
|
||||
changeState();
|
||||
}
|
||||
};
|
||||
wifiManager.startScan();
|
||||
handler.postDelayed(timeoutListener, WIFI_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a location lookup from cache
|
||||
*/
|
||||
private void startCache() {
|
||||
Log.d(TAG, "Starting cache lookup.");
|
||||
currentState = LocationState.CACHE;
|
||||
Position p = app.getLocationStore().findPosition(currentNetworks, NETWORK_MINIMUM);
|
||||
if (p != null) {
|
||||
Log.d(TAG, "Using cached location.");
|
||||
// update the user interface
|
||||
// update the user interface
|
||||
Coordinate c = new Coordinate();
|
||||
c.setLatitude(p.getLatitude());
|
||||
c.setLongitude(p.getLongitude());
|
||||
app.getRepository().gpsPosition.setValue(c);
|
||||
// create a release
|
||||
long now = System.currentTimeMillis();
|
||||
ReleasedLocation update = createLocation();
|
||||
update.setAvailability(ReleasedLocation.AvailabilityEnum.CACHED);
|
||||
update.setTimestamp(now);
|
||||
update.setCoordinate(new Coordinate());
|
||||
update.getCoordinate().setLongitude(p.getLongitude());
|
||||
update.getCoordinate().setLatitude(p.getLatitude());
|
||||
update.setAccuracy(p.getPrecision());
|
||||
update.setAltitude(p.getAltitude());
|
||||
update.setProvider(p.getProvider());
|
||||
app.getLocationStore().addUpdate(update);
|
||||
// update the usage time and the networks
|
||||
p.setUsageTime(now);
|
||||
p.getNetworks().clear();
|
||||
p.getNetworks().addAll(currentNetworks);
|
||||
app.getLocationStore().setPosition(p);
|
||||
// signal success
|
||||
resetState(true);
|
||||
} else {
|
||||
changeState();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a cleanup for gps.
|
||||
*/
|
||||
private void cleanupGps() {
|
||||
locationManager.removeUpdates(locationListener);
|
||||
cleanupTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a cleanup for wifi.
|
||||
*/
|
||||
private void cleanupWifi() {
|
||||
unregisterReceiver(wifiListener);
|
||||
cleanupTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a cleanup for network.
|
||||
*/
|
||||
private void cleanupNet() {
|
||||
locationManager.removeUpdates(locationListener);
|
||||
cleanupTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a cleanup of the timeout listener.
|
||||
*/
|
||||
private void cleanupTimeout() {
|
||||
if (timeoutListener != null) {
|
||||
handler.removeCallbacks(timeoutListener);
|
||||
timeoutListener = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the wifi scan has completed in time.
|
||||
*
|
||||
* @param results The results.
|
||||
*/
|
||||
private void setScan(List<ScanResult> results) {
|
||||
List<Network> networks = new ArrayList<>();
|
||||
for (ScanResult r: results) {
|
||||
Network n = new Network();
|
||||
n.setBssid(r.BSSID);
|
||||
n.setRssi(r.level);
|
||||
networks.add(n);
|
||||
}
|
||||
this.currentNetworks = networks;
|
||||
changeState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the location has been determined using gps or network.
|
||||
*
|
||||
* @param location The location.
|
||||
*/
|
||||
private void setLocation(Location location) {
|
||||
if (location == null) return; // should not happen
|
||||
// cleanup based on type
|
||||
if (currentState == LocationState.GPS) cleanupGps();
|
||||
if (currentState == LocationState.NET) cleanupNet();
|
||||
// update the user interface
|
||||
Coordinate c = new Coordinate();
|
||||
c.setLatitude(location.getLatitude());
|
||||
c.setLongitude(location.getLongitude());
|
||||
app.getRepository().gpsPosition.setValue(c);
|
||||
// create final location
|
||||
ReleasedLocation update = createLocation();
|
||||
update.setCoordinate(new Coordinate());
|
||||
update.getCoordinate().setLatitude(location.getLatitude());
|
||||
update.getCoordinate().setLongitude(location.getLongitude());
|
||||
if (location.hasAccuracy()) update.setAccuracy((double)location.getAccuracy());
|
||||
if (location.hasAltitude()) update.setAltitude(location.getAltitude());
|
||||
if (location.hasBearing()) update.setBearing((double)location.getBearing());
|
||||
if (location.hasSpeed()) update.setSpeed((double)location.getSpeed());
|
||||
update.setProvider(location.getProvider());
|
||||
update.setTimestamp(location.getTime());
|
||||
update.setAvailability(ReleasedLocation.AvailabilityEnum.FRESH);
|
||||
app.getLocationStore().addUpdate(update);
|
||||
// store location in cache
|
||||
if (hasMinimumNetworks()) {
|
||||
Position p = new Position();
|
||||
p.setLatitude(location.getLatitude());
|
||||
p.setLongitude(location.getLongitude());
|
||||
p.setCreationTime(System.currentTimeMillis());
|
||||
p.setProvider(location.getProvider());
|
||||
p.setUsageTime(p.getCreationTime());
|
||||
if (location.hasAccuracy()) p.setPrecision((double)location.getAccuracy());
|
||||
if (location.hasAltitude()) p.setAltitude(location.getAltitude());
|
||||
p.getNetworks().addAll(currentNetworks);
|
||||
app.getLocationStore().addPosition(p);
|
||||
}
|
||||
// reset the state machine
|
||||
resetState(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a released location and initializes the values
|
||||
* that must be determined based on the app settings.
|
||||
*
|
||||
* @return The initialized location.
|
||||
*/
|
||||
private ReleasedLocation createLocation() {
|
||||
ReleasedLocation location = new ReleasedLocation();
|
||||
location.setVersion(getVersion());
|
||||
location.setSharable(isSharable());
|
||||
location.setAnalyzable(isAnalyzable());
|
||||
return location;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the location is sharable.
|
||||
*
|
||||
* @return True if sharable, false otherwise.
|
||||
*/
|
||||
private boolean isSharable() {
|
||||
// TODO: make this a preference
|
||||
return app.getRepository().getResearchAllowed(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the location is analyzable.
|
||||
*
|
||||
* @return True if analyzable.
|
||||
*/
|
||||
private boolean isAnalyzable() {
|
||||
DeviceHandle handle = app.getRepository().deviceHandle.getValue();
|
||||
return handle != null && handle.getUser() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the app version or -1 if an error occurs.
|
||||
*
|
||||
* @return The app version.
|
||||
*/
|
||||
private int getVersion() {
|
||||
try {
|
||||
PackageInfo info = this.getPackageManager().getPackageInfo(getPackageName(), 0);
|
||||
return info.versionCode;
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the current networks exceed the minimum network threshold.
|
||||
*
|
||||
* @return True if there are more than the network minimum networks.
|
||||
*/
|
||||
private boolean hasMinimumNetworks() {
|
||||
return currentNetworks != null && currentNetworks.size() >= NETWORK_MINIMUM;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines whether wifi is available.
|
||||
*
|
||||
* @return True if wifi is enabled or can scan without being enabled.
|
||||
*/
|
||||
private boolean canUseWifi() {
|
||||
return hasWifiPermissions() && (wifiManager.isWifiEnabled() || canScanAlways());
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether wifi can scan without being available.
|
||||
*
|
||||
* @return True if wifi can scan without being available.
|
||||
*/
|
||||
private boolean canScanAlways() {
|
||||
try {
|
||||
Method m = WifiManager.class.getMethod("isScanAlwaysAvailable");
|
||||
Object o = m.invoke(wifiManager);
|
||||
return (Boolean)o;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the gps provider can be used.
|
||||
*
|
||||
* @return True if gps is available, enabled and we have all permissions.
|
||||
*/
|
||||
private boolean canUseGps() {
|
||||
return canUseProvider(LocationManager.GPS_PROVIDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the network provider can be used.
|
||||
*
|
||||
* @return True if network is available, enabled and we have all permissions.
|
||||
*/
|
||||
private boolean canUseNetwork() {
|
||||
return canUseProvider(LocationManager.NETWORK_PROVIDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a particular location provider can be used.
|
||||
*
|
||||
* @param provider The provider.
|
||||
* @return True if we have all permissions and the provider is available and enabled.
|
||||
*/
|
||||
private boolean canUseProvider(String provider) {
|
||||
return hasLocationPermissions() && locationManager.getAllProviders().contains(provider) &&
|
||||
locationManager.isProviderEnabled(provider);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the app has the permissions to capture location.
|
||||
*
|
||||
* @return True if the app has permission to capture locations.
|
||||
*/
|
||||
private boolean hasLocationPermissions() {
|
||||
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
|
||||
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the permissions for wifi are assigned.
|
||||
*
|
||||
* @return True if the wifi permissions are granted.
|
||||
*/
|
||||
private boolean hasWifiPermissions() {
|
||||
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the service, if it is not running already.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public static void runService(Context context) {
|
||||
Intent intent = new Intent();
|
||||
intent.setClass(context, LocationService.class);
|
||||
context.startService(intent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules the service for periodic execution.
|
||||
*
|
||||
* @param context The context used to schedule this.
|
||||
*/
|
||||
private static void scheduleExecution(Context context) {
|
||||
PendingIntent pending = createIntent(context);
|
||||
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
|
||||
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + LOCALIZATION_TIMEOUT / 2, LOCALIZATION_TIMEOUT / 2, pending);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the periodic service execution.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
private static void cancelExecution(Context context) {
|
||||
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
|
||||
manager.cancel(createIntent(context));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a pending intent to start or cancel the periodic service execution.
|
||||
*
|
||||
* @param context The context.
|
||||
* @return The pending intent.
|
||||
*/
|
||||
private static PendingIntent createIntent(Context context) {
|
||||
Intent intent = new Intent();
|
||||
intent.setClass(context, LocationService.class);
|
||||
intent.putExtra(EXTRA_ALARM, true);
|
||||
return PendingIntent.getService(context, ALARM_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the intent is a periodic execution.
|
||||
*
|
||||
* @param intent The intent.
|
||||
* @return True if the intent is a periodic execution by the alarm manager.
|
||||
*/
|
||||
private static boolean isPeriodicExecution(Intent intent) {
|
||||
|
||||
try {
|
||||
if (intent == null) return false;
|
||||
return intent.getBooleanExtra(EXTRA_ALARM, false);
|
||||
} catch (Exception e) {
|
||||
Log.d(TAG, "Invalid intent, cannot extract alarm although it is defined.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
/**
|
||||
* The state that the service is currently in. The
|
||||
* basic state machine runs from idle to wifi and
|
||||
* then based on the result to net or gps unless
|
||||
* the wifi state is sufficient to perform localization.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public enum LocationState {
|
||||
|
||||
/**
|
||||
* The initial state where the service has not done
|
||||
* anything.
|
||||
*/
|
||||
IDLE,
|
||||
/**
|
||||
* The wifi scanning state where the service determines
|
||||
* the available wifi networks. When the state completes,
|
||||
* the service determines a) whether there is a cached location
|
||||
* and b) if not, whether to use network or gps to localization.
|
||||
*/
|
||||
WIFI,
|
||||
/**
|
||||
* The state in which we are performing a cache lookup.
|
||||
*/
|
||||
CACHE,
|
||||
/**
|
||||
* The network localization state where the service tries
|
||||
* to acquire a position fix using the network provider.
|
||||
*/
|
||||
NET,
|
||||
/**
|
||||
* The gps localization state where the service tries
|
||||
* to acquire a position fix using the gps provider.
|
||||
*/
|
||||
GPS
|
||||
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteException;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Log;
|
||||
import com.maptology.android.app.notice.NoticeContract;
|
||||
import com.maptology.android.feign.model.Coordinate;
|
||||
import com.maptology.android.feign.model.ReleasedLocation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The application interface for the location database.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationStore {
|
||||
|
||||
/**
|
||||
* The log tag to be used in log messages.
|
||||
*/
|
||||
protected static final String TAG = "LocationStore";
|
||||
|
||||
/**
|
||||
* The reference to the sqlite db.
|
||||
*/
|
||||
protected @Nullable SQLiteDatabase db;
|
||||
|
||||
/**
|
||||
* Creates a new notice store from the context.
|
||||
*
|
||||
* @param context The context.
|
||||
*/
|
||||
public LocationStore(@NonNull Context context) {
|
||||
LocationHelper helper = new LocationHelper(context);
|
||||
try {
|
||||
db = helper.getWritableDatabase();
|
||||
// enable referential integrity checks
|
||||
// with cascading deletes, etc.
|
||||
db.execSQL("PRAGMA foreign_keys=ON;");
|
||||
} catch (SQLiteException e) {
|
||||
Log.e(TAG, "Failed to open LocationStore database.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new position.
|
||||
*
|
||||
* @param p The position to add.
|
||||
*/
|
||||
public void addPosition(Position p) {
|
||||
if (db == null) return;
|
||||
db.beginTransaction();
|
||||
try {
|
||||
// add the position
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(LocationContract.Position.LATITUDE, p.getLatitude());
|
||||
values.put(LocationContract.Position.LONGITUDE, p.getLongitude());
|
||||
values.put(LocationContract.Position.ALTITUDE, p.getAltitude());
|
||||
values.put(LocationContract.Position.CREATION_TIME, p.getCreationTime());
|
||||
values.put(LocationContract.Position.USAGE_TIME, p.getUsageTime());
|
||||
values.put(LocationContract.Position.PRECISION, p.getPrecision());
|
||||
values.put(LocationContract.Position.PROVIDER, p.getProvider());
|
||||
db.insert(LocationContract.Position.TABLE, null, values);
|
||||
// get the position id
|
||||
p.setId(getPositionId());
|
||||
// add the networks
|
||||
for (Network n: p.getNetworks()) {
|
||||
addNetwork(p.getId(), n);
|
||||
}
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last created position id.
|
||||
*
|
||||
* @return The last created position id.
|
||||
*/
|
||||
private long getPositionId() {
|
||||
return getCreatedId(LocationContract.Position.TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last created network id.
|
||||
*
|
||||
* @return The last created network id.
|
||||
*/
|
||||
private long getNetworkId() {
|
||||
return getCreatedId(LocationContract.Network.TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last created id of the specified table.
|
||||
*
|
||||
* @param table The table.
|
||||
* @return The last created id or 0, if not possible.
|
||||
*/
|
||||
private long getCreatedId(String table) {
|
||||
if (db == null) return 0;
|
||||
Cursor c = db.rawQuery("SELECT last_insert_rowid() FROM " + table, null);
|
||||
long id = 0;
|
||||
if (c.moveToNext()) {
|
||||
id = c.getLong(0);
|
||||
}
|
||||
c.close();
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a network for the position.
|
||||
*
|
||||
* @param position The position.
|
||||
* @param n The network.
|
||||
*/
|
||||
private void addNetwork(long position, Network n) {
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(LocationContract.Network.POSITION, position);
|
||||
values.put(LocationContract.Network.BSSID, n.getBssid());
|
||||
values.put(LocationContract.Network.RSSI, n.getRssi());
|
||||
db.insert(LocationContract.Network.TABLE, null, values);
|
||||
n.setId(getNetworkId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of networks for a position.
|
||||
*
|
||||
* @param position The position.
|
||||
* @return The list of networks.
|
||||
*/
|
||||
private List<Network> getNetworks(long position) {
|
||||
List<Network> result = new ArrayList<>();
|
||||
if (db == null) return result;
|
||||
Cursor c = db.query(LocationContract.Network.TABLE, new String[] {
|
||||
LocationContract.Network.ID,
|
||||
LocationContract.Network.BSSID,
|
||||
LocationContract.Network.RSSI,
|
||||
|
||||
}, LocationContract.Network.POSITION + " = " + position, null, null, null, null);
|
||||
while (c.moveToNext()) {
|
||||
Network n = new Network();
|
||||
n.setId(c.getLong(0));
|
||||
n.setBssid(c.getString(1));
|
||||
n.setRssi(c.getInt(2));
|
||||
result.add(n);
|
||||
}
|
||||
c.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all networks from the position.
|
||||
*
|
||||
* @param position The position.
|
||||
*/
|
||||
private void removeNetworks(long position) {
|
||||
db.execSQL("DELETE FROM " + LocationContract.Network.TABLE + " WHERE " + LocationContract.Network.POSITION + " = " + position);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the position.
|
||||
*
|
||||
* @param p The position.
|
||||
*/
|
||||
public void setPosition(Position p) {
|
||||
if (db == null) return;
|
||||
db.beginTransaction();
|
||||
try {
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(LocationContract.Position.LATITUDE, p.getLatitude());
|
||||
values.put(LocationContract.Position.LONGITUDE, p.getLongitude());
|
||||
values.put(LocationContract.Position.ALTITUDE, p.getAltitude());
|
||||
values.put(LocationContract.Position.CREATION_TIME, p.getCreationTime());
|
||||
values.put(LocationContract.Position.USAGE_TIME, p.getUsageTime());
|
||||
values.put(LocationContract.Position.PRECISION, p.getPrecision());
|
||||
values.put(LocationContract.Position.PROVIDER, p.getProvider());
|
||||
db.update(LocationContract.Position.TABLE, values, LocationContract.Position.ID + " = " + p.getId(), null);
|
||||
removeNetworks(p.getId());
|
||||
for (Network n: p.getNetworks()) {
|
||||
addNetwork(p.getId(), n);
|
||||
}
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the position with the specified id.
|
||||
*
|
||||
* @param id The id to load.
|
||||
* @return The position with its networks.
|
||||
*/
|
||||
public Position getPosition(long id) {
|
||||
Position result = null;
|
||||
if (db == null) return result;
|
||||
db.beginTransaction();
|
||||
try {
|
||||
Cursor c = db.query(LocationContract.Position.TABLE, new String[] {
|
||||
LocationContract.Position.LATITUDE,
|
||||
LocationContract.Position.LONGITUDE,
|
||||
LocationContract.Position.ALTITUDE,
|
||||
LocationContract.Position.PRECISION,
|
||||
LocationContract.Position.PROVIDER,
|
||||
LocationContract.Position.CREATION_TIME,
|
||||
LocationContract.Position.USAGE_TIME},
|
||||
LocationContract.Position.ID + " = " + id,
|
||||
null, null, null, null);
|
||||
if (c.moveToNext()) {
|
||||
result = new Position();
|
||||
result.setId(id);
|
||||
result.setLatitude(c.getDouble(0));
|
||||
result.setLongitude(c.getDouble(1));
|
||||
result.setAltitude(c.isNull(2)?null:c.getDouble(2));
|
||||
result.setPrecision(c.isNull(3)?null:c.getDouble(3));
|
||||
result.setProvider(c.getString(4));
|
||||
result.setCreationTime(c.getLong(5));
|
||||
result.setUsageTime(c.getLong(6));
|
||||
result.getNetworks().addAll(getNetworks(id));
|
||||
}
|
||||
c.close();
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expires all positions whose usage time is smaller than the specified timestamp.
|
||||
*
|
||||
* @param time The time to delete.
|
||||
*/
|
||||
public void expirePositions(long time) {
|
||||
db.execSQL("DELETE FROM " + LocationContract.Position.TABLE + " WHERE " + LocationContract.Position.USAGE_TIME + " < " + time);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Finds the best cached position for the list of detected networks.
|
||||
*
|
||||
* @param networks The networks.
|
||||
* @param minimumMatching The minimum number of matching networks.
|
||||
* @return The position or null, if no match is good enough.
|
||||
*/
|
||||
public Position findPosition(List<Network> networks, int minimumMatching) {
|
||||
if (networks.size() == 0 || networks.size() < minimumMatching) return null;
|
||||
if (db == null) return null;
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (int i = 0, s = networks.size(); i < s; i++) {
|
||||
b.append("\"");
|
||||
b.append(networks.get(i).getBssid());
|
||||
b.append("\"");
|
||||
if (i < s - 1) {
|
||||
b.append(", ");
|
||||
}
|
||||
}
|
||||
Position best = null;
|
||||
int matches = 0;
|
||||
double distance = 0;
|
||||
db.beginTransaction();
|
||||
try {
|
||||
Cursor c = db.query(true, LocationContract.Network.TABLE,
|
||||
new String[] { LocationContract.Network.POSITION},
|
||||
LocationContract.Network.BSSID + " IN (" + b.toString() + ")",
|
||||
null, null, null, null, null);
|
||||
while (c.moveToNext()) {
|
||||
Position p = getPosition(c.getLong(0));
|
||||
if (p != null) {
|
||||
long d = p.getDistance(networks);
|
||||
int m = p.getMatches(networks);
|
||||
if (m > minimumMatching && (m > matches || (m == matches && d < distance))) {
|
||||
best = p;
|
||||
matches = m;
|
||||
distance = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
c.close();
|
||||
db.setTransactionSuccessful();
|
||||
} finally {
|
||||
db.endTransaction();
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of ids for the next updates.
|
||||
*
|
||||
* @param limit The maximum number of ids.
|
||||
* @return The list of ids.
|
||||
*/
|
||||
public List<Long> getUpdates(int limit) {
|
||||
List<Long> result = new ArrayList<>();
|
||||
if (db == null) return result;
|
||||
Cursor c = db.query(LocationContract.Update.TABLE, new String[] { LocationContract.Update.ID }, null, null, null, null, LocationContract.Update.ID + " ASC");
|
||||
while (c.moveToNext() && result.size() < limit) {
|
||||
result.add(c.getLong(0));
|
||||
}
|
||||
c.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an update.
|
||||
*
|
||||
* @param location The update to add.
|
||||
*/
|
||||
public void addUpdate(ReleasedLocation location) {
|
||||
if (db == null) return;
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(LocationContract.Update.TIMESTAMP, location.getTimestamp());
|
||||
values.put(LocationContract.Update.PROVIDER, location.getProvider());
|
||||
values.put(LocationContract.Update.AVAILABILITY, location.getAvailability()==null?0:location.getAvailability().ordinal());
|
||||
if (location.getCoordinate() != null) {
|
||||
values.put(LocationContract.Update.LATITUDE, location.getCoordinate().getLatitude());
|
||||
values.put(LocationContract.Update.LONGITUDE, location.getCoordinate().getLongitude());
|
||||
} else {
|
||||
values.put(LocationContract.Update.LATITUDE, (Double)null);
|
||||
values.put(LocationContract.Update.LONGITUDE, (Double)null);
|
||||
}
|
||||
values.put(LocationContract.Update.ALTITUDE, location.getAltitude());
|
||||
values.put(LocationContract.Update.PRECISION, location.getAccuracy());
|
||||
values.put(LocationContract.Update.BEARING, location.getBearing());
|
||||
values.put(LocationContract.Update.SPEED, location.getSpeed());
|
||||
values.put(LocationContract.Update.ANALYZABLE, location.getAnalyzable()==null?0:(location.getAnalyzable()?1:0));
|
||||
values.put(LocationContract.Update.SHARABLE, location.getSharable()==null?0:(location.getSharable()?1:0));
|
||||
values.put(LocationContract.Update.VERSION, location.getVersion()==null?0:location.getVersion());
|
||||
db.insert(LocationContract.Update.TABLE, null, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the update with the specified id.
|
||||
*
|
||||
* @param id The id.
|
||||
* @return The location or null, if not found.
|
||||
*/
|
||||
public ReleasedLocation getUpdate(long id) {
|
||||
ReleasedLocation r = null;
|
||||
if (db == null) return null;
|
||||
Cursor c = db.query(LocationContract.Update.TABLE, new String[]{
|
||||
LocationContract.Update.PROVIDER,
|
||||
LocationContract.Update.TIMESTAMP,
|
||||
LocationContract.Update.AVAILABILITY,
|
||||
LocationContract.Update.SHARABLE,
|
||||
LocationContract.Update.ANALYZABLE,
|
||||
LocationContract.Update.VERSION,
|
||||
LocationContract.Update.BEARING,
|
||||
LocationContract.Update.SPEED,
|
||||
LocationContract.Update.PRECISION,
|
||||
LocationContract.Update.ALTITUDE,
|
||||
LocationContract.Update.LATITUDE,
|
||||
LocationContract.Update.LONGITUDE
|
||||
}, LocationContract.Update.ID + " = " + id, null, null, null, null);
|
||||
if (c.moveToNext()) {
|
||||
r = new ReleasedLocation();
|
||||
r.setProvider(c.getString(0));
|
||||
r.setTimestamp(c.getLong(1));
|
||||
r.setAvailability(ReleasedLocation.AvailabilityEnum.values()[c.getInt(2)]);
|
||||
r.setSharable(!(c.isNull(3) || c.getInt(3) == 0));
|
||||
r.setAnalyzable(!(c.isNull(4) || c.getInt(4) == 0));
|
||||
r.setVersion(c.getInt(5));
|
||||
r.setBearing(c.isNull(6)?null:c.getDouble(6));
|
||||
r.setSpeed(c.isNull(7)?null:c.getDouble(7));
|
||||
r.setAccuracy(c.isNull(8)?null:c.getDouble(8));
|
||||
r.setAltitude(c.isNull(9)?null:c.getDouble(9));
|
||||
if (c.isNull(10) || c.isNull(11)) {
|
||||
r.setCoordinate(null);
|
||||
} else {
|
||||
Coordinate cor = new Coordinate();
|
||||
cor.setLatitude(c.getDouble(10));
|
||||
cor.setLongitude(c.getDouble(11));
|
||||
r.setCoordinate(cor);
|
||||
}
|
||||
}
|
||||
c.close();;
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the update with the specified id.
|
||||
*
|
||||
* @param id The id to delete.
|
||||
*/
|
||||
public void removeUpdate(long id) {
|
||||
if (db == null) return;
|
||||
db.execSQL("DELETE FROM " + LocationContract.Update.TABLE + " WHERE " + LocationContract.Update.ID + " = " + id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of updates stored.
|
||||
*
|
||||
* @return The number of updates.
|
||||
*/
|
||||
public long getUpdateCount() {
|
||||
return getCount(LocationContract.Update.TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of positions stored.
|
||||
*
|
||||
* @return The number of positions.
|
||||
*/
|
||||
public long getPositionCount() {
|
||||
return getCount(LocationContract.Position.TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of networks stored.
|
||||
*
|
||||
* @return The number of networks.
|
||||
*/
|
||||
public long getNetworkCount() {
|
||||
return getCount(LocationContract.Network.TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element count in the table.
|
||||
*
|
||||
* @param table The table name.
|
||||
* @return The element count.
|
||||
*/
|
||||
private long getCount(String table) {
|
||||
if (db == null) return 0;
|
||||
Cursor c = db.query(table, new String[] {"COUNT(*)"}, null, null, null, null, null);
|
||||
long result = 0;
|
||||
if (c.moveToNext()) {
|
||||
result = c.getLong(0);
|
||||
}
|
||||
c.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all contents from the database. This
|
||||
* is primarily intended for testing.
|
||||
*/
|
||||
public void clear() {
|
||||
for (String table: new String[] { NoticeContract.Notice.TABLE, NoticeContract.Message.TABLE, NoticeContract.Setting.TABLE }) {
|
||||
db.execSQL("DELETE FROM " + table);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
import android.os.AsyncTask;
|
||||
import android.util.Log;
|
||||
import com.maptology.android.app.repository.Repository;
|
||||
import com.maptology.android.app.util.MaptologyApp;
|
||||
import com.maptology.android.feign.api.DefaultApi;
|
||||
import com.maptology.android.feign.model.LocationUpdate;
|
||||
import com.maptology.android.feign.model.ReleasedLocation;
|
||||
import feign.FeignException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* An async task that uploads the locations that have not been
|
||||
* uploaded so far.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationUploadTask extends AsyncTask<Void, Void, Void> {
|
||||
|
||||
/**
|
||||
* The log tag for debugging.
|
||||
*/
|
||||
private static final String TAG = "LocationUploadTask";
|
||||
|
||||
/**
|
||||
* The maximum number of locations to be uploaded in one batch.
|
||||
*/
|
||||
private static final int MAXIMUM_BATCH_SIZE = 100;
|
||||
|
||||
/**
|
||||
* The maptology app.
|
||||
*/
|
||||
private MaptologyApp app;
|
||||
|
||||
/**
|
||||
* The respository of the app.
|
||||
*/
|
||||
private Repository repository;
|
||||
|
||||
/**
|
||||
* The location store.
|
||||
*/
|
||||
private LocationStore store;
|
||||
|
||||
/**
|
||||
* The api client to execute the task.
|
||||
*/
|
||||
private DefaultApi apiClient;
|
||||
|
||||
/**
|
||||
* Creates a new location upload task using the app
|
||||
* which provides access to the location store and the
|
||||
* repository.
|
||||
*
|
||||
* @param app The app to perform the upload for.
|
||||
*/
|
||||
public LocationUploadTask(MaptologyApp app) {
|
||||
this.app = app;
|
||||
this.repository = app.getRepository();
|
||||
this.store = app.getLocationStore();
|
||||
this.apiClient = app.getApiClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the task.
|
||||
*/
|
||||
public void execute() {
|
||||
Log.d(TAG, "Starting upload.");
|
||||
this.repository.uploadingLocations.setValue(Boolean.TRUE);
|
||||
super.execute(new Void[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void doInBackground(Void... voids) {
|
||||
Log.d(TAG, "Running upload in background.");
|
||||
while (true) {
|
||||
List<Long> updateIds = store.getUpdates(MAXIMUM_BATCH_SIZE);
|
||||
List<ReleasedLocation> locations = new ArrayList<>();
|
||||
for (Long id: updateIds) {
|
||||
ReleasedLocation r = store.getUpdate(id);
|
||||
if (r != null) locations.add(r);
|
||||
}
|
||||
if (locations.size() == 0) {
|
||||
Log.d(TAG, "Everything uploaded.");
|
||||
break;
|
||||
} else {
|
||||
Log.d(TAG, "Uploading " + locations.size() + " updates.");
|
||||
}
|
||||
LocationUpdate update = new LocationUpdate();
|
||||
update.setLocations(locations);
|
||||
try {
|
||||
apiClient.addLocations(update);
|
||||
Log.d(TAG, "Upload succeeded.");
|
||||
} catch (FeignException e) {
|
||||
Log.d(TAG, "Upload failed with " + e.status() + " " + e.getMessage() + ".");
|
||||
break;
|
||||
}
|
||||
for (Long id: updateIds) {
|
||||
store.removeUpdate(id);
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "Finishing background upload.");
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPostExecute(Void aVoid) {
|
||||
super.onPostExecute(aVoid);
|
||||
this.repository.uploadingLocations.setValue(Boolean.FALSE);
|
||||
Log.d(TAG, "Finished upload.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
/**
|
||||
* A stored network.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Network {
|
||||
|
||||
/**
|
||||
* The id in the database.
|
||||
*/
|
||||
private long id;
|
||||
|
||||
/**
|
||||
* The bssid of the network.
|
||||
*/
|
||||
private String bssid;
|
||||
|
||||
/**
|
||||
* The rssi of the network.
|
||||
*/
|
||||
private int rssi;
|
||||
|
||||
/**
|
||||
* Returns the id of the network.
|
||||
*
|
||||
* @return The database id.
|
||||
*/
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database id.
|
||||
*
|
||||
* @param id The database id.
|
||||
*/
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the mac address of the network.
|
||||
*
|
||||
* @return The mac address of the network.
|
||||
*/
|
||||
public String getBssid() {
|
||||
return bssid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the mac address of the network.
|
||||
*
|
||||
* @param bssid The mac address of the network.
|
||||
*/
|
||||
public void setBssid(String bssid) {
|
||||
this.bssid = bssid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the signal strength.
|
||||
*
|
||||
* @return The signal strength.
|
||||
*/
|
||||
public int getRssi() {
|
||||
return rssi;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the signal strength.
|
||||
*
|
||||
* @param rssi The signal strength.
|
||||
*/
|
||||
public void setRssi(int rssi) {
|
||||
this.rssi = rssi;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ID(" + id + ") BSSID(" + bssid + ") RSSI(" + rssi + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package com.maptology.android.app.location;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A cached position with associated networks.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class Position {
|
||||
|
||||
/**
|
||||
* The id of the position.
|
||||
*/
|
||||
private long id;
|
||||
/**
|
||||
* The networks of the position.
|
||||
*/
|
||||
private List<Network> networks = new ArrayList<>();
|
||||
/**
|
||||
* The longitude of the position.
|
||||
*/
|
||||
private double longitude;
|
||||
/**
|
||||
* The latitude of the position.
|
||||
*/
|
||||
private double latitude;
|
||||
/**
|
||||
* The optional altitude of the position.
|
||||
*/
|
||||
private Double altitude;
|
||||
/**
|
||||
* The optional precision of the position.
|
||||
*/
|
||||
private Double precision;
|
||||
/**
|
||||
* The non-null provider of the position.
|
||||
*/
|
||||
private String provider;
|
||||
/**
|
||||
* The last used time of the position.
|
||||
*/
|
||||
private long usageTime;
|
||||
/**
|
||||
* The creation time of the position.
|
||||
*/
|
||||
private long creationTime;
|
||||
|
||||
/**
|
||||
* Returns the database id.
|
||||
*
|
||||
* @return The database id.
|
||||
*/
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database id.
|
||||
*
|
||||
* @param id The database id.
|
||||
*/
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of networks.
|
||||
*
|
||||
* @return The list of networks.
|
||||
*/
|
||||
public List<Network> getNetworks() {
|
||||
return networks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the longitude.
|
||||
*
|
||||
* @return The longitude.
|
||||
*/
|
||||
public double getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the longitude.
|
||||
*
|
||||
* @param longitude The longitude.
|
||||
*/
|
||||
public void setLongitude(double longitude) {
|
||||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the latitude.
|
||||
*
|
||||
* @return The latitude.
|
||||
*/
|
||||
public double getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the latitude.
|
||||
*
|
||||
* @param latitude The latitude.
|
||||
*/
|
||||
public void setLatitude(double latitude) {
|
||||
this.latitude = latitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the optional altitude.
|
||||
*
|
||||
* @return The optional altitude or null.
|
||||
*/
|
||||
public Double getAltitude() {
|
||||
return altitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the optional altitude.
|
||||
*
|
||||
* @param altitude The altitude or null.
|
||||
*/
|
||||
public void setAltitude(Double altitude) {
|
||||
this.altitude = altitude;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the optional precision.
|
||||
*
|
||||
* @return The precision in meters or null.
|
||||
*/
|
||||
public Double getPrecision() {
|
||||
return precision;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the precision.
|
||||
*
|
||||
* @param precision The precision.
|
||||
*/
|
||||
public void setPrecision(Double precision) {
|
||||
this.precision = precision;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the provider.
|
||||
*
|
||||
* @return The provider.
|
||||
*/
|
||||
public String getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the provider.
|
||||
*
|
||||
* @param provider The provider.
|
||||
*/
|
||||
public void setProvider(String provider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last usage time in system time mills.
|
||||
*
|
||||
* @return The usage time.
|
||||
*/
|
||||
public long getUsageTime() {
|
||||
return usageTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the usage time in system time millis.
|
||||
*
|
||||
* @param usageTime The usage time.
|
||||
*/
|
||||
public void setUsageTime(long usageTime) {
|
||||
this.usageTime = usageTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the creation time in system time millis.
|
||||
*
|
||||
* @return The creation time.
|
||||
*/
|
||||
public long getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the creation time.
|
||||
*
|
||||
* @param creationTime The creation time.
|
||||
*/
|
||||
public void setCreationTime(long creationTime) {
|
||||
this.creationTime = creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of matching networks.
|
||||
*
|
||||
* @param networks The networks to match against.
|
||||
* @return The number of matching networks.
|
||||
*/
|
||||
public int getMatches(List<Network> networks) {
|
||||
Set<String> bssids = new HashSet<>();
|
||||
for (Network n: this.networks) {
|
||||
bssids.add(n.getBssid());
|
||||
}
|
||||
int count = 0;
|
||||
for (Network n: networks) {
|
||||
if (bssids.contains(n.getBssid())) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the distance in vector space squared.
|
||||
*
|
||||
* @param networks The networks.
|
||||
* @return The squared distance sum in vector space.
|
||||
*/
|
||||
public long getDistance(List<Network> networks) {
|
||||
Map<String, Network> nets = new HashMap<>();
|
||||
for (Network n: this.networks) {
|
||||
nets.put(n.getBssid(), n);
|
||||
}
|
||||
long distance = 0;
|
||||
for (Network n: networks) {
|
||||
int rssiOut = -100;
|
||||
Network o = nets.get(n.getBssid());
|
||||
if (o != null) {
|
||||
rssiOut = o.getRssi();
|
||||
}
|
||||
int rssiIn = n.getRssi();
|
||||
int delta = rssiIn - rssiOut;
|
||||
distance += delta * delta;
|
||||
}
|
||||
return distance;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder b = new StringBuilder();
|
||||
b.append("ID(" + id + ") ");
|
||||
b.append("CREATION_TIME(" + creationTime + ") ");
|
||||
b.append("USAGE_TIME(" + usageTime + ") ");
|
||||
b.append("PROVIDER(" + provider + ") ");
|
||||
b.append("LATITUDE(" + latitude + ") ");
|
||||
b.append("LONGITUDE(" + longitude + ") ");
|
||||
b.append("ALTITUDE(" + altitude + ") ");
|
||||
b.append("PRECISION(" + precision + ") ");
|
||||
b.append("NETWORKS( ");
|
||||
for (Network n: networks) {
|
||||
b.append(n.toString());
|
||||
b.append(" ");
|
||||
}
|
||||
b.append(")");
|
||||
return b.toString();
|
||||
}
|
||||
}
|
||||
@@ -7,27 +7,23 @@ import android.location.LocationManager;
|
||||
import android.location.LocationProvider;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
import com.maptology.android.feign.model.Coordinate;
|
||||
|
||||
/**
|
||||
* The location value contains the current coordinate
|
||||
* of the device, which may be null.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationValue extends ActiveValue<Location> {
|
||||
public class LocationValue extends Value<Coordinate> {
|
||||
|
||||
/**
|
||||
* Creates a new value using the repo.
|
||||
*
|
||||
* @param repository The repo to use.
|
||||
*/
|
||||
public LocationValue(Repository repository) {
|
||||
super(repository);
|
||||
}
|
||||
|
||||
public LocationValue(Repository repository, Location initialValue) {
|
||||
super(repository, initialValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.maptology.android.app.repository;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.location.Location;
|
||||
import com.maptology.android.feign.model.Coordinate;
|
||||
import com.maptology.android.feign.model.DeviceHandle;
|
||||
import com.maptology.android.feign.model.ShareInfo;
|
||||
|
||||
@@ -24,9 +25,18 @@ public class Repository {
|
||||
*/
|
||||
public final Value<Boolean> loadingNotices = new Value<>(this, Boolean.FALSE);
|
||||
|
||||
/**
|
||||
* A flag that determines whether there is a running location upload
|
||||
* task. This flag should be considered read-only for all other classes
|
||||
* than the location upload task.
|
||||
*/
|
||||
public final Value<Boolean> uploadingLocations = new Value<>(this, Boolean.FALSE);
|
||||
|
||||
|
||||
public final Value<Boolean> loadingShares = new Value<>(this,Boolean.FALSE);
|
||||
|
||||
public final ActiveValue<Location> gpsPosition = new LocationValue(this, null);
|
||||
|
||||
public final Value<Coordinate> gpsPosition = new LocationValue(this);
|
||||
|
||||
public final Value<DeviceHandle> deviceHandle = new Value<DeviceHandle>(this, null);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.maptology.android.app.repository.IValueListener;
|
||||
import com.maptology.android.app.repository.Repository;
|
||||
import com.maptology.android.app.repository.Value;
|
||||
import com.maptology.android.app.OutgoingShare.ShareStore;
|
||||
import com.maptology.android.app.location.LocationStore;
|
||||
import com.maptology.android.feign.ApiClient;
|
||||
import com.maptology.android.feign.api.DefaultApi;
|
||||
import com.maptology.android.feign.model.DeviceHandle;
|
||||
@@ -49,6 +50,12 @@ public class MaptologyApp extends Application {
|
||||
*/
|
||||
protected NoticeStore noticeStore;
|
||||
|
||||
/**
|
||||
* The location store to store updates
|
||||
* and to cache locations.
|
||||
*/
|
||||
protected LocationStore locationStore;
|
||||
|
||||
/**
|
||||
* The api client to access the server.
|
||||
*/
|
||||
@@ -97,6 +104,19 @@ public class MaptologyApp extends Application {
|
||||
return noticeStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the database to store location updates
|
||||
* and to cache locations.
|
||||
*
|
||||
* @return The location store.
|
||||
*/
|
||||
public LocationStore getLocationStore() {
|
||||
if (locationStore == null) {
|
||||
locationStore = new LocationStore(this);
|
||||
}
|
||||
return locationStore;
|
||||
}
|
||||
|
||||
public ShareStore getShareStore(){
|
||||
if(shareStore==null){
|
||||
shareStore=new ShareStore(this);
|
||||
@@ -151,6 +171,7 @@ public class MaptologyApp extends Application {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: why do you put trivial calls in this class?
|
||||
public DateFormat getDateFormat(){
|
||||
return DateFormat.getDateInstance(DateFormat.DEFAULT);
|
||||
}
|
||||
|
||||
@@ -1,423 +0,0 @@
|
||||
package com.maptology.android.app.util;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.Notification;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteOpenHelper;
|
||||
import android.location.Location;
|
||||
import android.location.LocationListener;
|
||||
import android.location.LocationManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
import android.util.Log;
|
||||
import com.maptology.android.app.MainActivity;
|
||||
import com.maptology.android.app.R;
|
||||
import com.maptology.android.app.repository.Repository;
|
||||
import android.database.Cursor;
|
||||
|
||||
/**
|
||||
* Tasks of this service:
|
||||
* - Manage registered location updates (Enable/Disable for Battery saving)
|
||||
* - Pre-Process
|
||||
*/
|
||||
public class MaptologyService extends Service {
|
||||
|
||||
private final String TAG = MaptologyService.class.getSimpleName();
|
||||
|
||||
/**
|
||||
* ID of the notification: Each Notification to be displayed differently needs a unique one or it will replace the previous one
|
||||
*/
|
||||
private final int NOTIFICATION_ID = 1;
|
||||
|
||||
private LocationManager locationManager;
|
||||
private MyLocationListener locationListener;
|
||||
private LocationCache locationCache;
|
||||
private boolean isGPSEnabled, isNetworkEnabled;
|
||||
|
||||
/**
|
||||
* Since the onStartCommand is called regulary by the Alarm manager, we need some way to remember if we already subscribed
|
||||
*/
|
||||
private boolean isReceivingUpdates = false;
|
||||
|
||||
/**
|
||||
* Minimum difference in milliseconds and meters required to trigger a position update
|
||||
*/
|
||||
private final int MIN_TIME_DELTA = 10 * 1000;
|
||||
private final int MIN_DIST_DELTA = 5;
|
||||
|
||||
|
||||
private Repository repository;
|
||||
|
||||
|
||||
/**
|
||||
* @param context
|
||||
* Starts the Service
|
||||
* Tells the AlarmManager to regulary fire an Intent booting the Service and keeping it alive
|
||||
*/
|
||||
public static void runService(Context context) {
|
||||
/* Directly start the Service (alarm only triggers after the set first set period) */
|
||||
Intent serviceIntent = new Intent(context, MaptologyService.class);
|
||||
context.startService(serviceIntent);
|
||||
|
||||
/* Setup alarm timer */
|
||||
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
|
||||
Intent intent = new Intent(context, MaptologyService.AlarmReceiver.class);
|
||||
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
|
||||
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000,
|
||||
pendingIntent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reacts on the broadcast set up in runService()
|
||||
* Starts the Service and/or calls the Service-Routine
|
||||
*/
|
||||
public static class AlarmReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
Intent serviceIntent = new Intent(context, MaptologyService.class);
|
||||
context.startService(serviceIntent);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers on boot and tries to start the service
|
||||
*
|
||||
* todo Figure out why it does not work...
|
||||
*/
|
||||
public static class BootReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
runService(context);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Spawns or updates the Notification in the Android-Drawer
|
||||
*
|
||||
* @param subtext The smaller info text to show below Title
|
||||
*/
|
||||
private void showNotification(String subtext) {
|
||||
|
||||
/* Build the intent which will be used upon tapping on the Notification */
|
||||
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
|
||||
notificationIntent.setAction(Intent.ACTION_MAIN);
|
||||
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
|
||||
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(
|
||||
getApplicationContext(),
|
||||
0,
|
||||
notificationIntent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
|
||||
Notification serviceNotification = new NotificationCompat.Builder(getApplicationContext())
|
||||
.setContentTitle(getString(R.string.task_notification_title))
|
||||
.setContentText(subtext)
|
||||
.setSmallIcon(R.drawable.icon_notification_small)
|
||||
.setWhen(System.currentTimeMillis())
|
||||
.setContentIntent(contentIntent)
|
||||
.build();
|
||||
startForeground(NOTIFICATION_ID, serviceNotification);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called at the beginning of the Service Lifecycle
|
||||
*/
|
||||
@Override
|
||||
public void onCreate() {
|
||||
Log.d(TAG, "Creating Service Instance");
|
||||
|
||||
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
|
||||
repository = getRepository();
|
||||
if (repository == null) {
|
||||
Log.e(TAG, "Missing Application Repo!");
|
||||
}
|
||||
|
||||
locationListener = new MyLocationListener();
|
||||
locationCache = new LocationCache(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsibscribes from Updates and removes the notification
|
||||
*/
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
Log.d(TAG, "Destroying Service Instance");
|
||||
locationManager.removeUpdates(locationListener);
|
||||
stopForeground(true);
|
||||
locationCache.close();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* In our case this Method is called regulary due to the AlarmManager usage!
|
||||
* Checks and manages current Subscription status
|
||||
*
|
||||
* @param intent
|
||||
* @param flags
|
||||
* @param startId
|
||||
* @return
|
||||
* todo Enables and disables GPS updates when not available for a longer period of time (tunnels, buildings...)
|
||||
* Triggers transmission of cached location values to the Online-API
|
||||
*/
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
Log.d(TAG, "onStartCommand: " + intent.toString());
|
||||
|
||||
showNotification("Location-Service Running");
|
||||
|
||||
/* Should not happen, but well... */
|
||||
if (locationManager == null) {
|
||||
Log.e(TAG, "No LocationManager available");
|
||||
stopSelf();
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
/* Check for available Providers */
|
||||
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
|
||||
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
|
||||
|
||||
if (!isGPSEnabled && !isNetworkEnabled) {
|
||||
Log.w(TAG, "No Location Provider available on Service-Start");
|
||||
}
|
||||
|
||||
/* Register Listener */
|
||||
if (!isReceivingUpdates) {
|
||||
enableLocationUpdates(true, true);
|
||||
isReceivingUpdates = true;
|
||||
}
|
||||
|
||||
/* Store last known Position in repo */
|
||||
if(repository!=null) {
|
||||
repository.gpsPosition.setValue(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
|
||||
}
|
||||
|
||||
/* Update current Share-Count */
|
||||
showNotification("Active Shares: ");
|
||||
|
||||
/* Process the cache Periodically */
|
||||
processCache();
|
||||
|
||||
/* No need for sticky since we trigger the service periodically anyway */
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the LocationListener for selected providers
|
||||
*
|
||||
* @param useGPS Enable GPS
|
||||
* @param useNetwork Enable Network
|
||||
*/
|
||||
private void enableLocationUpdates(boolean useGPS, boolean useNetwork) {
|
||||
locationManager.removeUpdates(locationListener);
|
||||
|
||||
if (useGPS && isGPSEnabled) {
|
||||
try {
|
||||
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_DELTA, MIN_DIST_DELTA, locationListener);
|
||||
Log.d(TAG, "Subscribed for GPS");
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to subscribe for GPS Location Updates: " + e.getMessage());
|
||||
isGPSEnabled = false;
|
||||
}
|
||||
}
|
||||
if (useNetwork && isNetworkEnabled) {
|
||||
try {
|
||||
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_DELTA, MIN_DIST_DELTA, locationListener);
|
||||
Log.d(TAG, "Subscribed for Network");
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to subscribe for GPS Location Updates: " + e.getMessage());
|
||||
isNetworkEnabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processCache() {
|
||||
Location l;
|
||||
while (null != (l = locationCache.getOldest())) {
|
||||
/* API Call goes here :) */
|
||||
locationCache.removeLocation(l);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
/* We never bind the Service */
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the application repository
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public @Nullable
|
||||
Repository getRepository() {
|
||||
MaptologyApp app = getApp();
|
||||
if (app != null) return app.getRepository();
|
||||
else return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the application context and casts it
|
||||
* to the appropriate type.
|
||||
*
|
||||
* @return The application context.
|
||||
*/
|
||||
public @Nullable
|
||||
MaptologyApp getApp() {
|
||||
Context c = getApplicationContext();
|
||||
if (c instanceof MaptologyApp) {
|
||||
// this cast will always work unless the maptology app
|
||||
// is taken out of the application manifest
|
||||
return (MaptologyApp) c.getApplicationContext();
|
||||
} else {
|
||||
Log.d(TAG, "Application context does not have the expected type (check app manifest).");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class MyLocationListener implements LocationListener {
|
||||
/**
|
||||
* Last locations received by the Listener
|
||||
*/
|
||||
Location lastGPSLocation, lastNetworkLocation;
|
||||
|
||||
/**
|
||||
* Passes each Position to the Repository and the Cache
|
||||
* Also stores the last Position for each seperate Provider
|
||||
*
|
||||
* @param location
|
||||
*/
|
||||
@Override
|
||||
public void onLocationChanged(Location location) {
|
||||
Log.d(TAG, "Got a location update from " + location.getProvider() + " - Accuracy: " + location.getAccuracy() + " at lng " + location.getLatitude() + " lat " + location.getLongitude());
|
||||
|
||||
if (repository != null)
|
||||
repository.gpsPosition.setValue(location);
|
||||
|
||||
if (locationCache != null)
|
||||
locationCache.addLocation(location);
|
||||
|
||||
if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER))
|
||||
lastNetworkLocation = location;
|
||||
else if (location.getProvider().equals(LocationManager.GPS_PROVIDER))
|
||||
lastGPSLocation = location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStatusChanged(String s, int i, Bundle bundle) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderEnabled(String s) {
|
||||
Log.d(TAG, "Provider enabled: " + s);
|
||||
if (s.equals(LocationManager.NETWORK_PROVIDER))
|
||||
isNetworkEnabled = true;
|
||||
else if (s.equals(LocationManager.GPS_PROVIDER))
|
||||
isGPSEnabled = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProviderDisabled(String s) {
|
||||
Log.d(TAG, "Provider disabled: " + s);
|
||||
if (s.equals(LocationManager.NETWORK_PROVIDER))
|
||||
isNetworkEnabled = false;
|
||||
else if (s.equals(LocationManager.GPS_PROVIDER))
|
||||
isGPSEnabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to store and retrieve Locations which could not be sent to the Online-API directly
|
||||
* Keeps a simple SQLite Database to do so
|
||||
*/
|
||||
private class LocationCache extends SQLiteOpenHelper {
|
||||
private static final String DB_NAME = "location_cache.db";
|
||||
private static final int DB_VERSION = 1;
|
||||
SQLiteDatabase db = null;
|
||||
|
||||
|
||||
public LocationCache(Context context) {
|
||||
super(context, DB_NAME, null, DB_VERSION);
|
||||
db = getWritableDatabase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate(SQLiteDatabase sqLiteDatabase) {
|
||||
sqLiteDatabase.execSQL("CREATE TABLE locations (time INTEGER PRIMARY KEY, provider TEXT, lng REAL, lat REAL, alt REAL)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
|
||||
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS locations");
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a Location to the database
|
||||
*
|
||||
* @param l
|
||||
*/
|
||||
public void addLocation(Location l) {
|
||||
ContentValues values = new ContentValues();
|
||||
values.put("time", l.getTime());
|
||||
values.put("provider", l.getProvider());
|
||||
values.put("lng", l.getLongitude());
|
||||
values.put("lat", l.getLatitude());
|
||||
|
||||
// db.insert("locations", null, values);
|
||||
Log.d(TAG, "Added location: "+l.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the oldest location in the Database
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public @Nullable
|
||||
Location getOldest() {
|
||||
String rawQuery = "SELECT time,provider,lng,lat FROM locations WHERE time = (SELECT min(time) FROM locations)";
|
||||
Cursor cursor = db.rawQuery(rawQuery, null);
|
||||
|
||||
if (cursor == null || cursor.getCount() < 1)
|
||||
return null;
|
||||
|
||||
cursor.moveToFirst();
|
||||
|
||||
cursor.close();
|
||||
return null;
|
||||
/*Location l = new Location(cursor.getString(cursor.getColumnIndex("provider") ));
|
||||
l.setTime(cursor.getLong(0));
|
||||
l.setLongitude(cursor.getDouble(2));
|
||||
l.setLatitude(cursor.getDouble(3));
|
||||
|
||||
return l;*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a location from the Database
|
||||
*
|
||||
* @param l
|
||||
*/
|
||||
public void removeLocation(@NonNull Location l) {
|
||||
String where = "time=?";
|
||||
String[] values = new String[]{Long.toString(l.getTime())};
|
||||
if(db.delete("location", where, values) <= 0)
|
||||
Log.e(TAG, "Delete Failed");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,12 @@
|
||||
android:layout_margin="16dp">
|
||||
|
||||
<android.support.v7.widget.AppCompatEditText
|
||||
android:id="@+id/input_email"
|
||||
android:id="@+id/input_login_name"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="6dp"
|
||||
android:hint="@string/email"
|
||||
android:inputType="textEmailAddress"
|
||||
android:hint="@string/login_name"
|
||||
android:inputType="text"
|
||||
style="@style/input"/>
|
||||
|
||||
<android.support.v7.widget.AppCompatEditText
|
||||
|
||||
@@ -1,51 +1,53 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="share_message">Nachricht</string>
|
||||
<string name="accept_continue">Akzeptieren & weiter</string>
|
||||
<string name="app_permission_desc">Möchen Sie Ihren Standort anonym zu Forschungszwecken freigeben?</string>
|
||||
<string name="app_permission_desc_long">Möchen Sie Ihren Standort anonym zu Forschungszwecken freigeben? Sie können
|
||||
<string name="share_message">Nachricht</string>
|
||||
<string name="accept_continue">Akzeptieren & weiter</string>
|
||||
<string name="app_permission_desc">Möchen Sie Ihren Standort anonym zu Forschungszwecken freigeben?</string>
|
||||
<string name="app_permission_desc_long">Möchen Sie Ihren Standort anonym zu Forschungszwecken freigeben? Sie können
|
||||
diese Einstellung jederzeit ändern.
|
||||
</string>
|
||||
<string name="app_version">Version</string>
|
||||
<string name="app_version_desc">App Version</string>
|
||||
<string name="application_long">Maptology App</string>
|
||||
<string name="cancel">Abbrechen</string>
|
||||
<string name="email">E-Mail Adresse</string>
|
||||
<string name="expiration_time">Ablaufzeit</string>
|
||||
<string name="friends_button">Freunde</string>
|
||||
<string name="generateLink_button">Link generieren</string>
|
||||
<string name="language_code">de</string>
|
||||
<string name="location_request_msg">Die App benötigt Ihren Standort, um richtig zu funktionieren. Bitte erlauben Sie
|
||||
der App, beim nächsten App-Start Ihren Standort zu verwenden.
|
||||
</string>
|
||||
<string name="location_request_title">Standortfreigabe benötigt</string>
|
||||
<string name="logged_out">Ausgeloggt</string>
|
||||
<string name="login">Login</string>
|
||||
<string name="logout">Logout</string>
|
||||
<string name="longitude_latitude">Längengrad: %1$g Breitengrad: %2$g</string>
|
||||
<string name="menu_notice_update_title">Update</string>
|
||||
<string name="menu_share_update_title">Update</string>
|
||||
<string name="nav_map">Karte</string>
|
||||
<string name="nav_settings">Einstellungen</string>
|
||||
<string name="nav_share">Standort teilen</string>
|
||||
<string name="nav_share_in">Erhaltene Shares</string>
|
||||
<string name="nav_share_out">Ausgehende Shares</string>
|
||||
<string name="no_login">Weiter ohne login</string>
|
||||
<string name="notice_notification_content">Tippen, um Details zu lesen.</string>
|
||||
<string name="ok">Ok</string>
|
||||
<string name="password">Passwort</string>
|
||||
<string name="register">Sie haben noch keinen Account? Registrieren Sie sich hier.</string>
|
||||
<string name="share_destination">Ziel</string>
|
||||
<string name="share_no_internet">Keine Internetverbindung</string>
|
||||
<string name="share_not_exist">Share existiert nicht</string>
|
||||
<string name="share_to">Teilen mit</string>
|
||||
<string name="task_notification_title">Maptology</string>
|
||||
<string name="view_notice_creation_title">Erstellt am:</string>
|
||||
<string name="view_notice_modification_title">Zuletzt geändert:</string>
|
||||
<string name="zoom_angle">Zoom: %1$d Winkel: %2$g</string>
|
||||
<string name="notice_notification_title">Maptology News</string>
|
||||
<string name="until">bis</string>
|
||||
<string name="drawer_title">Navigation</string>
|
||||
<string name="drawer_close">Navigation schließen</string>
|
||||
<string name="drawer_open">Navigation öffnen</string>
|
||||
</resources>
|
||||
<string name="app_version">Version</string>
|
||||
<string name="app_version_desc">App Version</string>
|
||||
<string name="application_long">Maptology App</string>
|
||||
<string name="cancel">Abbrechen</string>
|
||||
<string name="login_name">Anmeldename</string>
|
||||
<string name="expiration_time">Ablaufzeit</string>
|
||||
<string name="friends_button">Freunde</string>
|
||||
<string name="generateLink_button">Link generieren</string>
|
||||
<string name="language_code">de</string>
|
||||
<string name="location_request_msg">Die App benötigt Deinen Standort, um richtig zu funktionieren. Bitte erlaube der App beim nächsten Start Deinen Standort zu verwenden.</string>
|
||||
<string name="location_request_title">Standortfreigabe benötigt</string>
|
||||
<string name="logged_out">Abgemeldet</string>
|
||||
<string name="login">Anmelden</string>
|
||||
<string name="logout">Abmelden</string>
|
||||
<string name="login_failed_title">Anmeldung fehlgeschlagen</string>
|
||||
<string name="login_failed_msg">Bitte überprüfe Deinen Anmeldenamen und dein Passwort. Stelle sicher, dass du Deine E-Mail-Adresse verifiziert hast und du eine Internetverbindung hast.</string>
|
||||
<string name="device_failed_title">Gerät konnte nicht erstellt werden</string>
|
||||
<string name="device_failed_msg">Bitte prüfe Deine Internetverbindung und versuche es erneut.</string>
|
||||
<string name="longitude_latitude">Längengrad: %1$g Breitengrad: %2$g</string>
|
||||
<string name="menu_notice_update_title">Update</string>
|
||||
<string name="menu_share_update_title">Update</string>
|
||||
<string name="nav_map">Karte</string>
|
||||
<string name="nav_settings">Einstellungen</string>
|
||||
<string name="nav_share">Standort teilen</string>
|
||||
<string name="nav_share_in">Erhaltene Shares</string>
|
||||
<string name="nav_share_out">Ausgehende Shares</string>
|
||||
<string name="no_login">Weiter ohne Anmeldung</string>
|
||||
<string name="notice_notification_content">Tippen, um Details zu lesen.</string>
|
||||
<string name="ok">Ok</string>
|
||||
<string name="password">Passwort</string>
|
||||
<string name="register">Du hast noch keinen Account? Registriere Dich hier.</string>
|
||||
<string name="share_destination">Ziel</string>
|
||||
<string name="share_no_internet">Keine Internetverbindung</string>
|
||||
<string name="share_not_exist">Share existiert nicht</string>
|
||||
<string name="share_to">Teilen mit</string>
|
||||
<string name="task_notification_title">Maptology</string>
|
||||
<string name="view_notice_creation_title">Erstellt am:</string>
|
||||
<string name="view_notice_modification_title">Zuletzt geändert:</string>
|
||||
<string name="zoom_angle">Zoom: %1$d Winkel: %2$g</string>
|
||||
<string name="notice_notification_title">Maptology News</string>
|
||||
<string name="until">bis</string>
|
||||
<string name="drawer_title">Navigation</string>
|
||||
<string name="drawer_close">Navigation schließen</string>
|
||||
<string name="drawer_open">Navigation öffnen</string>
|
||||
</resources>
|
||||
|
||||
@@ -40,7 +40,6 @@
|
||||
<string name="nav_share_in">Incoming shares</string>
|
||||
<string name="nav_settings">Settings</string>
|
||||
|
||||
|
||||
<!--Share Fragment-->
|
||||
<string name="share_message">Message</string>
|
||||
<string name="share_destination">Destination</string>
|
||||
@@ -49,14 +48,17 @@
|
||||
<string name="menu_share_update_title">Update</string>
|
||||
|
||||
<!-- login and register -->
|
||||
<string name="email">E-Mail Address</string>
|
||||
<string name="login_name">Login name</string>
|
||||
<string name="password">Password</string>
|
||||
<string name="login">Login</string>
|
||||
<string name="logout">Logout</string>
|
||||
<string name="logged_out">Logged out.</string>
|
||||
<string name="register">You don\'t have an account yet? Register here.</string>
|
||||
<string name="no_login">Proceed without login</string>
|
||||
|
||||
<string name="login_failed_title">Login failed</string>
|
||||
<string name="login_failed_msg">Please check your username and password. Make sure that you verified your email address and have an internet connection.</string>
|
||||
<string name="device_failed_title">Creating device failed</string>
|
||||
<string name="device_failed_msg">Please check your internet connection and try again.</string>
|
||||
|
||||
<!--Incoming shares-->
|
||||
<string name="share_no_internet">No Internet connection</string>
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.maptology.android.app.test.location;
|
||||
|
||||
import android.location.LocationManager;
|
||||
import com.maptology.android.app.location.LocationStore;
|
||||
import com.maptology.android.app.notice.NoticeStore;
|
||||
import com.maptology.android.feign.model.Coordinate;
|
||||
import com.maptology.android.feign.model.ReleasedLocation;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.robolectric.RobolectricTestRunner;
|
||||
import org.robolectric.RuntimeEnvironment;
|
||||
import org.robolectric.shadows.ShadowLog;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests the basic operation of the location store.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner.class)
|
||||
public class LocationStoreTest {
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
// redirect the android log to std. out.
|
||||
// pretty useful during debugging but
|
||||
// ugly when done
|
||||
ShadowLog.stream = System.out;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddGetDeleteUpdates() {
|
||||
LocationStore store = new LocationStore(RuntimeEnvironment.application);
|
||||
ReleasedLocation r1 = createLocation(1);
|
||||
store.addUpdate(r1);
|
||||
Assert.assertEquals("Should contain one entry.", 1, store.getUpdateCount());
|
||||
List<Long> ids = store.getUpdates(100);
|
||||
Assert.assertEquals("Should contain one entry.", 1, ids.size());
|
||||
ReleasedLocation loaded = store.getUpdate(ids.get(0));
|
||||
Assert.assertNotNull("Loaded should exist.", loaded);
|
||||
assertEquals(r1, loaded);
|
||||
ReleasedLocation r2 = createLocation(2);
|
||||
store.addUpdate(r2);
|
||||
ids = store.getUpdates(100);
|
||||
Assert.assertEquals("Should contain two entries.", 2, ids.size());
|
||||
loaded = store.getUpdate(ids.get(1));
|
||||
Assert.assertNotNull("Loaded should exist.", loaded);
|
||||
assertEquals(r2, loaded);
|
||||
store.removeUpdate(ids.get(0));
|
||||
Assert.assertEquals("Should contain one entry.", 1, store.getUpdateCount());
|
||||
store.removeUpdate(ids.get(1));
|
||||
Assert.assertEquals("Should contain no entries", 0, store.getUpdateCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a location with a time stamp.
|
||||
*
|
||||
* @param time The time.
|
||||
* @return The location.
|
||||
*/
|
||||
private ReleasedLocation createLocation(long time) {
|
||||
ReleasedLocation r = new ReleasedLocation();
|
||||
r.setProvider(LocationManager.GPS_PROVIDER);
|
||||
r.setCoordinate(new Coordinate());
|
||||
r.getCoordinate().setLatitude(4d);
|
||||
r.getCoordinate().setLongitude(5d);
|
||||
r.setTimestamp(time);
|
||||
r.setAvailability(ReleasedLocation.AvailabilityEnum.CACHED);
|
||||
r.setSpeed(2d);
|
||||
r.setAltitude(3d);
|
||||
r.setBearing(5d);
|
||||
r.setSharable(true);
|
||||
r.setAnalyzable(true);
|
||||
r.setVersion(12);
|
||||
r.setAccuracy(1d);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to compare two locations.
|
||||
*
|
||||
* @param e The expected location.
|
||||
* @param a The actual location.
|
||||
*/
|
||||
private void assertEquals(ReleasedLocation e, ReleasedLocation a) {
|
||||
Assert.assertEquals("Provider should match.", e.getProvider(), a.getProvider());
|
||||
Assert.assertTrue("If coordinate null, then both.", (e.getCoordinate() == null && a.getCoordinate() == null) || (e.getCoordinate() != null && a.getCoordinate() != null));
|
||||
if (e.getCoordinate() != null) {
|
||||
Assert.assertEquals("Lat should match.", e.getCoordinate().getLatitude(), a.getCoordinate().getLatitude(), 0.00001);
|
||||
Assert.assertEquals("Lon should match.", e.getCoordinate().getLongitude(), a.getCoordinate().getLongitude(), 0.00001);
|
||||
}
|
||||
Assert.assertEquals("Time should match.", e.getTimestamp(), a.getTimestamp());
|
||||
Assert.assertEquals("Availability should match.", e.getAvailability(), a.getAvailability());
|
||||
Assert.assertEquals("Speeed should match.", e.getSpeed(), a.getSpeed());
|
||||
Assert.assertEquals("Alt should match.", e.getAltitude(), a.getAltitude());
|
||||
Assert.assertEquals("Bearing should match.", e.getBearing(), a.getBearing());
|
||||
Assert.assertEquals("Share should match.", e.getSharable(), a.getSharable());
|
||||
Assert.assertEquals("Analyze should match.", e.getAnalyzable(), a.getAnalyzable());
|
||||
Assert.assertEquals("Version should match.", e.getVersion(), a.getVersion());
|
||||
Assert.assertEquals("Accuracy should match.", e.getAccuracy(), a.getAccuracy());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.maptology.service.entity;
|
||||
|
||||
import javax.persistence.AttributeOverride;
|
||||
import javax.persistence.AttributeOverrides;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Embedded;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
@@ -50,6 +53,10 @@ public class LocationEntity extends AbstractEntity {
|
||||
* The (optional) coordinate of the location.
|
||||
*/
|
||||
@Embedded
|
||||
@AttributeOverrides({
|
||||
@AttributeOverride(name="latitude", column=@Column(nullable=true)),
|
||||
@AttributeOverride(name="longitude", column=@Column(nullable=true))
|
||||
})
|
||||
private EmbeddedCoordinate coordinate;
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,40 +1,63 @@
|
||||
<div class="animated fadeIn">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header">Meine Shares</div>
|
||||
<div class="card-body">
|
||||
<table class="table table-striped table-bordered dataTable no-footer" role="grid">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Share</th>
|
||||
<th class="text-center">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let privilege of privileges; let i = index">
|
||||
<td><a [routerLink]="['/maptology/map', privilege.token]">{{privilege.token}}</a></td>
|
||||
<!--
|
||||
<td class="text-center">
|
||||
<button *ngIf="!user.deleted == true; else undoButton" type="button" class="btn btn-danger" data-toggle="modal" (click)="showDeleteUserModal(i)">
|
||||
<i class="fa fa-trash-o"></i>
|
||||
</button>
|
||||
</td>
|
||||
-->
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<!-- Pagination -->
|
||||
<div class="row">
|
||||
<div class="col-sm-4">Page: {{currentPage}} / {{numPages}}</div>
|
||||
<div class="col-sm-8">
|
||||
<pagination [totalItems]="totalItems" [(ngModel)]="currentPage" [maxSize]="maxSize" class="pagination float-right"
|
||||
[boundaryLinks]="true" [rotate]="false" (numPages)="numPages = $event"
|
||||
(pageChanged)="pageChanged($event)"></pagination>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card">
|
||||
<div class="card-header">Meine Shares</div>
|
||||
<div class="card-body">
|
||||
<table class="table table-striped table-bordered dataTable no-footer" role="grid">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Share</th>
|
||||
<th>Message</th>
|
||||
<th>Destination</th>
|
||||
<th class="text-center">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let privilege of privileges; let i = index">
|
||||
<td><a [routerLink]="['/maptology/map', privilege.token]">{{privilege.token}}</a></td>
|
||||
<td>{{privilege.shareInfo.message}}</td>
|
||||
<td>{{privilege.shareInfo.destination}}</td>
|
||||
<td class="text-center">
|
||||
<button *ngIf="!privilege.deleted == true; else undoButton" type="button" class="btn btn-danger" data-toggle="modal" (click)="showDeletePrivilegeModal(i)">
|
||||
<i class="fa fa-trash-o"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<!-- Pagination -->
|
||||
<div class="row">
|
||||
<div class="col-sm-4">Page: {{currentPage}} / {{numPages}}</div>
|
||||
<div class="col-sm-8">
|
||||
<pagination [totalItems]="totalItems" [(ngModel)]="currentPage" [maxSize]="maxSize" class="pagination float-right"
|
||||
[boundaryLinks]="true" [rotate]="false" (numPages)="numPages = $event"
|
||||
(pageChanged)="pageChanged($event)"></pagination>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- modal view to delete user-->
|
||||
<div bsModal #deletePrivilegeModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-warning" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h4 class="modal-title">Delete Privilege</h4>
|
||||
<button type="button" class="close" (click)="hideDeletePrivilegeModal()" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Do you want to delete Privilege {{privileges[selectedPrivilegeId].token}}</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" (click)="hideDeletePrivilegeModal()">Cancel</button>
|
||||
<button type="button" class="btn btn-warning" (click)="deletePrivilege(selectedPrivilegeId)">Delete</button>
|
||||
</div>
|
||||
</div><!-- /.modal-content -->
|
||||
</div><!-- /.modal-dialog -->
|
||||
</div><!-- /.modal -->
|
||||
|
||||
@@ -24,10 +24,14 @@ export class SharesComponent implements OnInit {
|
||||
maxSize: number = 5;
|
||||
numPages: number = 0;
|
||||
|
||||
selectedPrivilegeId: number;
|
||||
|
||||
errorMessage: string;
|
||||
|
||||
refreshInterval;
|
||||
|
||||
@ViewChild('deletePrivilegeModal') deletePrivilegeModal;
|
||||
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
private privilegesService: PrivilegesService,
|
||||
@@ -79,4 +83,18 @@ export class SharesComponent implements OnInit {
|
||||
closeButton: true
|
||||
});
|
||||
}
|
||||
|
||||
showDeletePrivilegeModal(index: number) {
|
||||
// this.isModalShown = true;
|
||||
this.selectedPrivilegeId = index;
|
||||
this.deletePrivilegeModal.show();
|
||||
}
|
||||
|
||||
hideDeletePrivilegeModal() {
|
||||
this.deletePrivilegeModal.hide();
|
||||
}
|
||||
|
||||
deletePrivilege(selectedPrivilegeId: number) {
|
||||
alert(`About to delete privilege`);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user