Skip to content

Commit

Permalink
Added location tracking
Browse files Browse the repository at this point in the history
+ Only log in case of significant difference
+ Renamed Orientation object to Direction
+ Gradle update to 7.4.2
  • Loading branch information
vdeconinck committed May 3, 2023
1 parent 131f3b5 commit 4374524
Show file tree
Hide file tree
Showing 11 changed files with 370 additions and 116 deletions.
1 change: 1 addition & 0 deletions Main/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ android {
signingConfig signingConfigs.release
}
}
namespace 'info.deconinck.inclinometer'
}

dependencies {
Expand Down
3 changes: 1 addition & 2 deletions Main/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="info.deconinck.inclinometer">
xmlns:tools="http://schemas.android.com/tools">

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.BLUETOOTH" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import static info.deconinck.inclinometer.view.InclinometerView.MAX_TILT;
import static info.deconinck.inclinometer.view.InclinometerView.getAngleColor;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
Expand All @@ -18,7 +17,6 @@
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
Expand Down Expand Up @@ -71,7 +69,7 @@
import info.deconinck.inclinometer.dialog.AddressDialog;
import info.deconinck.inclinometer.dialog.AngleDialog;
import info.deconinck.inclinometer.dialog.SmoothingDialog;
import info.deconinck.inclinometer.model.Orientation;
import info.deconinck.inclinometer.model.Direction;
import info.deconinck.inclinometer.model.Session;
import info.deconinck.inclinometer.persistence.AppDatabase;
import info.deconinck.inclinometer.util.SharedUtil;
Expand Down Expand Up @@ -132,7 +130,8 @@ public class DataMonitorActivity extends FragmentActivity implements OnClickList
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothService mBluetoothService = null;
private String mConnectedDeviceName = null;
private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
private GpsTracker mGpsTracker = null;

public byte[] writeBuffer;
public byte[] readBuffer;
private Switch outputSwitch;
Expand Down Expand Up @@ -163,6 +162,7 @@ public class DataMonitorActivity extends FragmentActivity implements OnClickList
private Long sessionId;
private static long nextLogTime;
private Session selectedSession;
private Direction lastDirection = null;


private float norm(float x[]) {
Expand Down Expand Up @@ -491,7 +491,7 @@ public void recordData(byte fieldTypeByte) {
threshold = threshold.minusMonths(DB_PURGE_AFTER_MONTHS);
List<Session> obsoleteSessions = db.sessionDao().getSessionsOlderThan(threshold);
for (Session obsoleteSession : obsoleteSessions) {
db.orientationDao().deleteOrientationsForSession(obsoleteSession.id);
db.directionDao().deleteDirectionsForSession(obsoleteSession.id);
db.sessionDao().delete(obsoleteSession);
}

Expand All @@ -517,8 +517,11 @@ public void recordData(byte fieldTypeByte) {
float tilt = angle[1] - tiltCompensationAngle;

// Log values to DB
Orientation orientation = new Orientation(sessionId, roll, tilt);
db.orientationDao().insert(orientation);
Direction direction = new Direction(sessionId, mGpsTracker.getLongitude(), mGpsTracker.getLatitude(), roll, tilt);
if (direction.differsEnoughFrom(lastDirection)) {
db.directionDao().insert(direction);
lastDirection = direction;
}
// Show them as a notification
displayNotifications(roll, tilt);

Expand Down Expand Up @@ -634,15 +637,6 @@ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_LOCATION_REQUEST_CODE);
}
if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_LOCATION_REQUEST_CODE);
}
}

Window window = getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
Expand Down Expand Up @@ -693,6 +687,8 @@ public void onCreate(Bundle savedInstanceState) {


try {
mGpsTracker = new GpsTracker(DataMonitorActivity.this);

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
new AlertDialog.Builder(DataMonitorActivity.this)
Expand Down Expand Up @@ -1395,14 +1391,14 @@ public void onActivityResult(int requestCode, int resultCode, Intent data) {
case REQUEST_CREATE_FILE:
if (selectedSession != null) {
Toast.makeText(this, "Saving session " + selectedSession.id, Toast.LENGTH_SHORT).show();
new AsyncTask<Void, Void, List<Orientation>>() {
new AsyncTask<Void, Void, List<Direction>>() {
@Override
protected List<Orientation> doInBackground(Void... voids) {
return db.orientationDao().getOrientationsBySession(selectedSession.id);
protected List<Direction> doInBackground(Void... voids) {
return db.directionDao().getDirectionsBySession(selectedSession.id);
}

@Override
protected void onPostExecute(List<Orientation> orientations) {
protected void onPostExecute(List<Direction> directions) {
try {
OutputStream outputStream = getContentResolver().openOutputStream(data.getData());

Expand All @@ -1420,19 +1416,19 @@ protected void onPostExecute(List<Orientation> orientations) {
serializer.attribute("", "creator", getString(R.string.app_name));
serializer.attribute("", "version", getString(R.string.app_version));

for (Orientation orientation : orientations) {
for (Direction direction : directions) {
// Write the waypoint element
serializer.startTag("", "wpt");
serializer.attribute("", "lat", String.valueOf(orientation.latitude));
serializer.attribute("", "lon", String.valueOf(orientation.longitude));
serializer.attribute("", "lat", String.valueOf(direction.latitude));
serializer.attribute("", "lon", String.valueOf(direction.longitude));

// Write the child elements of the waypoint element
// serializer.startTag("", "ele");
// serializer.text("12.863281");
// serializer.endTag("", "ele");

serializer.startTag("", "time");
serializer.text(String.valueOf(orientation.getISOTimestamp()));
serializer.text(String.valueOf(direction.getISOTimestamp()));
serializer.endTag("", "time");

// serializer.startTag("", "name");
Expand All @@ -1448,10 +1444,10 @@ protected void onPostExecute(List<Orientation> orientations) {
serializer.startTag(INCLINOMETER_NS, "wptExtension");

serializer.startTag(INCLINOMETER_NS, "tilt");
serializer.text(String.valueOf(orientation.tilt));
serializer.text(String.valueOf(direction.tilt));
serializer.endTag(INCLINOMETER_NS, "tilt");
serializer.startTag(INCLINOMETER_NS, "roll");
serializer.text(String.valueOf(orientation.roll));
serializer.text(String.valueOf(direction.roll));
serializer.endTag(INCLINOMETER_NS, "roll");

serializer.endTag(INCLINOMETER_NS, "wptExtension");
Expand Down
224 changes: 224 additions & 0 deletions Main/src/main/java/info/deconinck/inclinometer/GpsTracker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
package info.deconinck.inclinometer;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

import androidx.core.app.ActivityCompat;

/**
* Taken from sample at https://www.howtodoandroid.com/get-current-location-android/
*/
public class GpsTracker extends Service implements LocationListener {

public static final String TAG = GpsTracker.class.getName();
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}

public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
//check the network permission
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d(TAG, "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
//check the network permission
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d(TAG, "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */

public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}
}

/**
* Function to get latitude
* */

public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */

public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */

public boolean canGetLocation() {
return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */

public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title
alertDialog.setTitle("GPS is settings");

// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Loading

0 comments on commit 4374524

Please sign in to comment.