Clean up code, reduce memory and make the world a better place

This commit is contained in:
Chet Henry
2014-12-05 12:56:06 -07:00
parent 1823e202ff
commit 54c4cd6daa
8 changed files with 122 additions and 226 deletions

View File

@@ -11,23 +11,29 @@ import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class CurrentValuesAdapter extends BaseAdapter {
public StartActivity context;
private StartActivity context;
public int[] keys;
public String[] values = new String[RideService.KEYS.length];
public String[] keyLabels = new String[RideService.KEYS.length];
public RelativeLayout[] lls = new RelativeLayout[RideService.KEYS.length];
public int size = 20;
public boolean imperial = false;
public int count = 0;
public static SharedPreferences.OnSharedPreferenceChangeListener spChanged;
private int[] keys;
private String[] values = new String[RideService.KEYS.length];
private String[] keyLabels = new String[RideService.KEYS.length];
private int size = 20;
private boolean imperial = false;
public CurrentValuesAdapter(StartActivity c) {
private GridView layout;
public CurrentValuesAdapter(StartActivity c, GridView tlayout) {
context = c;
layout = tlayout;
layout.setBackgroundColor(Color.BLACK);
layout.setVerticalSpacing(4);
layout.setHorizontalSpacing(4);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
Set<String> sensors = settings.getStringSet(context.getString(R.string.PREF_TRACKING_SENSORS), null);
size = Integer.valueOf(settings.getString(context.getString(R.string.PREF_TRACKING_SIZE), "20"));
@@ -62,7 +68,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String pkey) {
if(pkey == context.getString(R.string.PREF_TRACKING_SIZE)) {
size = Integer.valueOf(sharedPreferences.getString(context.getString(R.string.PREF_TRACKING_SIZE), "20"));
context.layout.setColumnWidth(getWidth());
setupWidth();
notifyDataSetChanged();
} else if (pkey == context.getString(R.string.PREF_TRACKING_SENSORS)) {
Set<String> sensors = sharedPreferences.getStringSet(context.getString(R.string.PREF_TRACKING_SENSORS), null);
@@ -73,7 +79,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
i++;
}
context.layout.setAdapter(CurrentValuesAdapter.this);
layout.setAdapter(CurrentValuesAdapter.this);
} else if (pkey == context.getString(R.string.PREF_TRACKING_IMPERIAL_UNITS)) {
imperial = sharedPreferences.getBoolean(pkey, false);
@@ -85,7 +91,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
);
}
public void updateKeyLables() {
private void updateKeyLables() {
if(!imperial) {
for(int key : keys) {
keyLabels[key] = RideService.KEYS[key].toString().toLowerCase();
@@ -113,7 +119,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
}
}
public RelativeLayout newRelativeLayout(int key) {
private RelativeLayout newRelativeLayout(int key) {
RelativeLayout view = new RelativeLayout(context);
view.setBackgroundColor(Color.WHITE);
@@ -145,7 +151,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
}
public TextView newValueTv(int key){
private TextView newValueTv(int key){
TextView tv = new TextView(context);
tv.setTextAppearance(context, android.R.attr.textAppearanceLarge);
tv.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
@@ -156,7 +162,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
}
public TextView newKeyTv(int key){
private TextView newKeyTv(int key){
TextView tv = new TextView(context);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
tv.setBackgroundColor(Color.LTGRAY);
@@ -260,7 +266,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
* returns the size of the cell basted on 8 chars wide and the configured size param
* @return int
*/
public int getWidth() {
private void setupWidth() {
TextView tv = new TextView(context);
tv.setTextAppearance(context, android.R.attr.textAppearanceLarge);
tv.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
@@ -269,7 +275,7 @@ public class CurrentValuesAdapter extends BaseAdapter {
Rect bounds = new Rect();
tv.getPaint().getTextBounds("9999.9", 0, "9999.9".length(), bounds);
return bounds.width() + 16;
layout.setColumnWidth(bounds.width() + 16);
}
}

View File

@@ -9,9 +9,7 @@ import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.Timer;
@@ -56,7 +54,6 @@ public class RideService extends Service
{
public static final int notifyID = 1; //Id of the notification in the top android bar that this class creates and alters
public static final int SECS = 0;
public static final int KPH = 1;
public static final int ALTITUDE = 2;
@@ -110,27 +107,20 @@ public class RideService extends Service
"press",
"lux"
};
public static final int TOTALSENSORS = RideService.KEYS.length;
public float[] currentValues = new float[RideService.TOTALSENSORS]; //float array of current values
public float[] snoopedValues = new float[RideService.TOTALSENSORS]; //float array of snooped values
public GzipWriter buf; //writes to log file buffered
public long startTime; //start time of the ride
public boolean rideStarted = false; //have we started logging the ride
public Boolean snoop = false; //should we log others ant+ devices
private Set<String> pairedAnts; //list of ant devices to pair with
private Timer timer; //timer class to control the periodic messages
private Timer timerUI; //timer class to control the periodic messages
private String emergencyNumbuer; //the number to send the messages to
public float[] currentValues = new float[RideService.KEYS.length]; //float array of current values
public GzipWriter buf; //writes to log file buffered
public long startTime; //start time of the ride
private boolean rideStarted = false; //have we started logging the ride
private Set<String> pairedAnts; //list of ant devices to pair with
private Timer timer; //timer class to control the periodic messages
private Timer timerUI; //timer class to control the periodic messages
private String emergencyNumbuer; //the number to send the messages to
public LinkedHashMap<String, Base<?>> sensors = new LinkedHashMap<String, Base<?>>();
//All other Android sensor class
MultiDeviceSearch mSearch; //Ant+ device search class to init connections
MultiDeviceSearch.SearchCallbacks mCallback; //Ant+ device class to setup sensors after they are found
MultiDeviceSearch.RssiCallback mRssiCallback; //Ant+ class to do something with the signal strength on device find
private Base<?>[] sensors;
private int sensor_index = 0;
MultiDeviceSearch mSearch; //Ant+ device search class to init connections
final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
@@ -141,6 +131,7 @@ public class RideService extends Service
public void handleMessage(Message msg) {
if(timerUI != null) {
timerUI.cancel();
timerUI = null;
}
timerUI = new Timer();
@@ -193,6 +184,7 @@ public class RideService extends Service
public boolean onUnbind (Intent intent) {
if(timerUI != null) {
timerUI.cancel();
timerUI = null;
}
return true;
@@ -286,27 +278,35 @@ public class RideService extends Service
buf.write(rideHeadder);
sensors.put("GPS", new Gps(this));
sensors.put("AndroidSensors", new Sensors(this));
if(pairedAnts != null) {
sensors = new Base<?>[pairedAnts.size() + 2];
} else {
sensors = new Base<?>[2];
}
sensors[sensor_index++] = new Gps(this);
sensors[sensor_index++] = new Sensors(this);
if(pairedAnts != null && !pairedAnts.isEmpty()){
mCallback = new MultiDeviceSearch.SearchCallbacks(){
MultiDeviceSearch.SearchCallbacks mCallback = new MultiDeviceSearch.SearchCallbacks(){
public void onDeviceFound(final MultiDeviceSearchResult deviceFound)
{
if (!deviceFound.isAlreadyConnected()) {
if(pairedAnts == null || pairedAnts.contains(Integer.toString(deviceFound.getAntDeviceNumber()))) {
launchConnection(deviceFound, false);
} else if (snoop) {
launchConnection(deviceFound, true);
launchConnection(deviceFound);
}
}
}
@Override
public void onSearchStopped(RequestAccessResult arg0) {}
public void onSearchStopped(RequestAccessResult arg0) {
mSearch = null;
}
};
mRssiCallback = new MultiDeviceSearch.RssiCallback() {
MultiDeviceSearch.RssiCallback mRssiCallback = new MultiDeviceSearch.RssiCallback() {
@Override
public void onRssiUpdate(final int resultId, final int rssi){}
};
@@ -430,8 +430,10 @@ public class RideService extends Service
phoneStop();
for (Map.Entry<String, Base<?>> entry : sensors.entrySet()) {
entry.getValue().onDestroy();
for(Base<?> sensor: sensors) {
if(sensor != null) {
sensor.onDestroy();
}
}
//stop the Ant+ search
@@ -442,10 +444,12 @@ public class RideService extends Service
//stop the phoneHome timer if we need to.
if(timer != null) {
timer.cancel();
timer = null;
}
if(timerUI != null) {
timerUI.cancel();
timerUI = null;
}
try {
@@ -459,19 +463,13 @@ public class RideService extends Service
}
//remove snooped sensors if they are not longer in range
public void releaseSnoopedSensor(Base<?> sensor) {
sensors.remove(sensor);
}
//launch ant+ connection
public void launchConnection(MultiDeviceSearchResult result, Boolean snoop) {
public void launchConnection(MultiDeviceSearchResult result) {
switch (result.getAntDeviceType()) {
case BIKE_CADENCE:
break;
case BIKE_POWER:
sensors.put(String.valueOf(result.getAntDeviceNumber()), new Power(result, this, snoop));
sensors[sensor_index++] = new Power(result, this);
break;
case BIKE_SPD:
break;
@@ -484,7 +482,7 @@ public class RideService extends Service
case WEIGHT_SCALE:
break;
case HEARTRATE:
sensors.put(String.valueOf(result.getAntDeviceNumber()), new HeartRate(result, this, snoop));
sensors[sensor_index++] = new HeartRate(result, this);
break;
case STRIDE_SDM:
break;

View File

@@ -1,12 +1,10 @@
package com.ridelogger;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
@@ -21,47 +19,12 @@ import android.widget.GridView;
import android.widget.Toast;
public class StartActivity extends FragmentActivity
{
Intent rsi;
GridView layout;
private RunningServiceInfo service;
Messenger mService = null;
boolean mIsBound;
BroadcastReceiver mReceiver;
{
private MenuItem startMenu;
private MenuItem stopMenu;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private CurrentValuesAdapter currentValuesAdapter;
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
updateValues(msg.getData());
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain();
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
}
};
private ServiceConnection mConnection;
CurrentValuesAdapter currentValuesAdapter;
@Override
@@ -96,15 +59,10 @@ public class StartActivity extends FragmentActivity
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
rsi = new Intent(this, RideService.class);
layout = (GridView) findViewById(R.id.LayoutData);
currentValuesAdapter = new CurrentValuesAdapter(this);
GridView layout = (GridView) findViewById(R.id.LayoutData);
currentValuesAdapter = new CurrentValuesAdapter(this, layout);
layout.setAdapter(currentValuesAdapter);
layout.setColumnWidth(currentValuesAdapter.getWidth());
layout.setBackgroundColor(Color.BLACK);
layout.setVerticalSpacing(4);
layout.setHorizontalSpacing(4);
}
@@ -122,15 +80,15 @@ public class StartActivity extends FragmentActivity
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
unBindToService();
}
/**
* setup the settings for the user
*/
public void setupSettings() {
private void setupSettings() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
@@ -142,6 +100,8 @@ public class StartActivity extends FragmentActivity
private void stopRide() {
Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.stopping_ride), Toast.LENGTH_LONG);
toast.show();
Intent rsi = new Intent(this, RideService.class);
this.stopService(rsi);
finish();
}
@@ -150,11 +110,32 @@ public class StartActivity extends FragmentActivity
/**
* tell the service to start sending us messages with current values
*/
public void bindToService() {
service = getServiceRunning(RideService.class);
private void bindToService() {
RunningServiceInfo service = getServiceRunning(RideService.class);
if(service != null) {
mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Messenger mService = new Messenger(service);
try {
Message msg = Message.obtain();
msg.replyTo = new Messenger(new Handler(){
@Override
public void handleMessage(Message msg_internal) {
updateValues(msg_internal.getData());
}
});
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
public void onServiceDisconnected(ComponentName className) {}
};
bindService(new Intent(StartActivity.this, RideService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
}
@@ -162,11 +143,11 @@ public class StartActivity extends FragmentActivity
/**
* tell the service to stop sending us messages with current values
*/
public void unBindToService() {
if (mIsBound) {
private void unBindToService() {
if (mConnection != null) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
mConnection = null;
}
}
@@ -175,9 +156,8 @@ public class StartActivity extends FragmentActivity
* update the text fields with current values
* @param bundle
*/
public void updateValues(Bundle bundle) {
float[] currentValues = (float[]) bundle.getSerializable("currentValues");
currentValuesAdapter.update(currentValues);
private void updateValues(Bundle bundle) {
currentValuesAdapter.update((float[]) bundle.getSerializable("currentValues"));
}
@@ -185,7 +165,7 @@ public class StartActivity extends FragmentActivity
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
service = getServiceRunning(RideService.class);
RunningServiceInfo service = getServiceRunning(RideService.class);
startMenu = menu.findItem(R.id.Start);
stopMenu = menu.findItem(R.id.Stop);
if(service == null) {
@@ -203,6 +183,7 @@ public class StartActivity extends FragmentActivity
* start the ride and notify the user of success
*/
private void startRide() {
Intent rsi = new Intent(this, RideService.class);
this.startService(rsi);
startMenu.setVisible(false);

View File

@@ -18,15 +18,11 @@ public class Ant extends Base<Object>
{
public PccReleaseHandle<?> releaseHandle; //Handle class
public IPluginAccessResultReceiver<?> mResultReceiver; //Receiver class
public Boolean snooped = false; //should we snoop others connections?
//setup listeners and logging
public Ant(MultiDeviceSearchResult result, RideService mContext) {
super(mContext);
}
public Ant(MultiDeviceSearchResult result, RideService mContext, Boolean pSnoop) {
//setup listeners and logging
public Ant(MultiDeviceSearchResult result, RideService mContext)
{
super(mContext);
snooped = pSnoop;
}
@@ -37,10 +33,6 @@ public class Ant extends Base<Object>
//if we lose a device zero out its values
if(newDeviceState.equals(DeviceState.DEAD)) {
zeroReadings();
if(snooped) {
releaseHandle.close(); // release ourselves if snooped
context.releaseSnoopedSensor(Ant.this);
}
}
}
};
@@ -56,43 +48,27 @@ public class Ant extends Base<Object>
@Override
public void writeData(int key, float value)
{
if(snooped) {
super.writeSnoopedData(key, value);
} else {
super.writeData(key, value);
}
super.writeData(key, value);
}
@Override
public void writeData(int[] keys, float[] values)
{
if(snooped) {
super.writeSnoopedData(keys, values);
} else {
super.writeData(keys, values);
}
super.writeData(keys, values);
}
@Override
public void alterCurrentData(int key, float value)
{
if(snooped) {
super.alterSnoopedData(key, value);
} else {
super.alterCurrentData(key, value);
}
{
super.alterCurrentData(key, value);
}
@Override
public void alterCurrentData(int[] keys, float[] values)
{
if(snooped) {
super.alterSnoopedData(keys, values);
} else {
super.alterCurrentData(keys, values);
}
super.alterCurrentData(keys, values);
}

View File

@@ -77,30 +77,8 @@ public class Base<T>
}
} catch (IOException e) {}
}
public void writeSnoopedData(int key, float value)
{
if(context.currentValues[key] != value) {
context.snoopedValues[RideService.SECS] = getTs();
context.snoopedValues[key] = value;
}
}
public void writeSnoopedData(int[] keys, float[] values)
{
context.snoopedValues[RideService.SECS] = getTs();
synchronized (context.snoopedValues) {
int i = 0;
for (int key : keys) {
context.snoopedValues[key] = values[i];
i++;
}
}
}
public void alterCurrentData(int key, float value)
{
synchronized (context.currentValues) {
@@ -109,16 +87,7 @@ public class Base<T>
writeCurrentData();
}
}
public void alterSnoopedData(int key, float value)
{
synchronized (context.snoopedValues) {
context.snoopedValues[RideService.SECS] = getTs();
context.snoopedValues[key] = value;
}
}
public void alterCurrentData(int[] keys, float[] values)
{
@@ -136,20 +105,6 @@ public class Base<T>
}
public void alterSnoopedData(int[] keys, float[] values)
{
synchronized (context.snoopedValues) {
context.snoopedValues[RideService.SECS] = getTs();
int i = 0;
for (int key : keys) {
context.snoopedValues[key] = values[i];
i++;
}
}
}
public void writeCurrentData()
{
try {

View File

@@ -25,12 +25,6 @@ public class HeartRate extends Ant
}
public HeartRate(MultiDeviceSearchResult result, RideService mContext, Boolean psnoop) {
super(result, mContext, psnoop);
releaseHandle = AntPlusHeartRatePcc.requestAccess(context, result.getAntDeviceNumber(), 0, mResultReceiver, mDeviceStateChangeReceiver);
}
public IPluginAccessResultReceiver<AntPlusHeartRatePcc> mResultReceiver = new IPluginAccessResultReceiver<AntPlusHeartRatePcc>() {
//Handle the result, connecting to events on success or reporting failure to user.
@Override

View File

@@ -39,15 +39,6 @@ public class Power extends Ant
}
public Power(MultiDeviceSearchResult result, RideService mContext, Boolean psnoop) {
super(result, mContext, psnoop);
releaseHandle = AntPlusBikePowerPcc.requestAccess(context, result.getAntDeviceNumber(), 0, mResultReceiver, mDeviceStateChangeReceiver);
wheelCircumferenceInMeters = new BigDecimal(
PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.PREF_WHEEL_SIZE), "2.096")
);
}
//Handle messages
protected IPluginAccessResultReceiver<AntPlusBikePowerPcc> mResultReceiver = new IPluginAccessResultReceiver<AntPlusBikePowerPcc>() {
//Handle the result, connecting to events on success or reporting failure to user.

View File

@@ -22,12 +22,6 @@ import android.preference.PreferenceManager;
public class Sensors extends Base<Object>
{
public static final double CRASHMAGNITUDE = 30.0;
private SensorManager mSensorManager;
private Sensor mLight;
private Sensor mAccel;
private Sensor mPress;
private Sensor mTemp;
private Sensor mField;
private SensorEventListener luxListner;
private SensorEventListener accelListner;
@@ -39,13 +33,13 @@ public class Sensors extends Base<Object>
{
super(mContext);
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
SensorManager mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
mAccel = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
mPress = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
mTemp = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
mField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Sensor mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Sensor mAccel = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
Sensor mPress = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
Sensor mTemp = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
Sensor mField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if(mLight != null) {
luxListner = new SensorEventListener() {
@@ -208,6 +202,7 @@ public class Sensors extends Base<Object>
@Override
public void onDestroy()
{
SensorManager mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
if(luxListner != null) {
mSensorManager.unregisterListener(luxListner);
}