How to handle live data of Accelerometer in android? - android

I need to perform Dynamic Time Wrapping(DTW) algorithm with some previously stored data and Accelerometer data. But I am unable to handle the huge amount of data coming from accelerometer. I need to determine a step. In order to do that I have stored a number of data previously and trying to match with the current data.
ArrayList<Double> test=new ArrayList<Double>();
public void onSensorChanged(SensorEvent event) {
double x=event.value[0];
double y=event.value[1];
double z=event.value[2];
double a=Math.sqrt(x*x+y*y+z*z);
test.add(a);
new ProgressRunner().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,x);
private class ProgressRunner extends AsyncTask<Double, Integer, Boolean>
{
#Override
protected Boolean doInBackground(Double... params) {
new Thread(new Runnable() {
#Override
public void run() {
double r=DTWDistance(StepSamples.sample1, standTest);
if(r<700) /* "Step Detected */
}
}).start();
return null;
}
But I am getting huge data coming from the sensor. My question is how do I handle this data and match with a sample data continuously. Also I have tested with a Log.d, I'm sure the problem is related to how I handle this Live data but I can't find a way out. Any suggestion would be helpful.
I have also tried this by doing it an interval of 2 sec but an OutOfMemeoryBoundsException throws
if((System.currentTimeMillis()-sTime)/1000>2){
new ProgressRunner().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,x);
}

One of the solution to address this problem is keeping a threshold for the change in the sensor values. If the change in deltaX, deltaY, deltaZ are greater then you can start the AsyncTask else dont.
Since u are not keeping any threshold values the number of threads u create is very huge in number.
EDIT 1:
Here is a link to a small tutorial that will help you to kick start... in this link he has used a time interval and a threshold for shaking the device... i bet this is a perfect solution for your requirement
Tutorial Link

Do you need to process every single value or are you fine processing every x (e.g. 0.1) seconds? I call a method that checks "now - lastProcessedTime". If that value is > 100ms, I will handle the data and update lastProcessedTime = now. If not, I will throw away the sensor value.

Related

Sending data our GPS coordinates properly

So basically what my problem is:
I am trying to make some sort of GPS app and in it I want to send the coordinates(longitude latitude) of where the user is to a server. It works well so far but I have reached a problem. I want to call my sendDataToserver() method periodically (every 5 seconds or so - BTW this is working correctly) method only after coordinates have been received from the GPS. But the thing is I cant figure out how to make ...(if statement or something)... the sendDataToserver() method to be called only after the coordinates have been received/changed. I am using an if statement right now:
if(lat != 0 && long !=0)
{
sendDataToserver();
}
but ... as you might have guessed 0.0 is a valid coordinate ... So can you give me an idea how to fix this problem so that sendDataToserver() could be called every 5 seconds or so and only if coordinates have been received?
First of all sending GPS data again & again to websever is not a good idea. This will dry your battery soon. To avoid this situation you should create a batch of 10-20 points togather in Json kind of format and then send those collected data togather.
Now coming to your GPS point, You need to use GpsStateListener. This listener has returns GPS_EVENT_FIRST_FIX when your device finds a GPS point. So you can write a condition that as soon as Gps State Listener returns this value you call your web-service call.
final Listener onGpsStatusChange = new GpsStatus.Listener() {
#Override
public void onGpsStatusChanged(int event) {
// TODO Auto-generated method stub
switch(event){
case GpsStatus.GPS_EVENT_STARTED:
// Started...
break ;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// First Fix...
break ;
case GpsStatus.GPS_EVENT_STOPPED:
// Stopped...
break ;
}
}
};
at first: do not use long as variable Name.
what about saving the last coordinate in a temporary variable like:
if(lastLat != newLat && lastLong != newLong) // code goes here
This might solve your problem:
unsigned long GPS_WAIT=5000;
curr_time= millis();
if(curr_time>=GPS_WAIT)
{
sendDataToserver();curr_time=0;
}else
{
curr_time= millis();
}

Android application programming: Filling a two-dimensional array in a thread

I am trying to calibrate an accelerometer, but I can't obtain the 6 sample values at 6 different acceleration readings required for the calibration. PreliminaryW is a double[6][3] array made to fill those sample values. It is 6 by 3 because each acceleration reading has an x, y, and a z component.
I am planning to sample them by pressing a button at the 6 different acceleration readings. This button makes "calibrate" true.
I ofcourse, first make "calibrating" true to start this thread.
For some unfathomable reason, preliminaryW[i] = currentAcc seems to be filling up from 0 to i with the same value instead of just i. I made sure that the currentAcc is different every time I press the "calibrate" button.
What is wrong with my code?
public synchronized void run() {
Log.d(TAG, "+ in Calibrator thread +");
int i = -1;
while (calibrating) {
if (calibrate) {
i = i + 1;
calibrate = false;
preliminaryW[i] = currentAcc;
if (i == 5) {
calibrating = false;
}
}
}
}
I'm not very familiar with the inner-workings of the accelerometer, and it's hard to decide why it's not working without seeing more of the code. For example, can you be sure that there's only one instance of the Thread, or are you creating multiple instances?
Why does this need to be in a Thread?
Looping like that is not good practice either, you should use wait/notify if you absolutely need a Thread. (more info at http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html)
I've drafted a class that does approximately what you want, but doesn't use threading. You could create a Calibrator and then call performCalibration() with each new value:
class Calibrator{
int count = 0;
double[][] preliminaryW = new double[6][3];
public void performCalibration(double[] currentAcc){
preliminaryW[count] = currentAcc;
count++;
}
}
without the Thread and "busy loop", you might be able to omit those flags for 'calibrate' and 'calibrating' which would certainly help debugging as well.
Good Luck!

Saving gyroscope data while capturing image

I'm quite new to Android and currently doing a little camera app that could save gyroscope/accelerometer data samples of the moment from camera shutter open till its close. Basically, I initialize gyro sensor in image capture button listener (with camera.takePicture()) and stop the sensor within ShutterCallback. Here is my question. Should I write the recorded sensor data to a .txt everytime I get a new sample or is there some clever method?
I wrote an app where I logged sensor data at the fastest rate (SensorManager.SENSOR_DELAY_FASTEST). I was worried about the performance issues related to constantly writing to a text file while doing other tasks, so I created an AsyncTask class to do it in the background. The following code worked fine for me, even if the app was left running for hours. In your case, since you only want to log for a short period of time, another idea would be to keep the log information in memory in a collection object (e.g. an ArrayList<>), and then log everything on the ShutterCallback.
public void LogSensor(long SystemTime, int SensorType, float[] SensorValues) {
String LogString = Integer.toString(SensorType);
for(int i=0; i<SensorValues.length; i++) LogString += "," + SensorValues[i];
(new LogSensor_in_background()).execute(SystemTime+","+LogString);
}
private class LogSensor_in_background extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... LogStrings) {
// do logging
return null; }
}

Android : Displaying score as a string on canvas is creating a new string per draw command. How do I get around this?

I'm making a game that displays some numbers on a canvas (score, time, etc).
The way that I currently do this is with the drawtext command on a canvas
// score is some int
draw(Canvas c) {
c.drawText(score+"", x, y, paintSyle);
}
I hear that object creation and garbage collection are expensive operations, and I think this is creating a new string every time it is called.
Right now my game with all bitmap drawing and everything jumps around from 25 to 60 fps. I'd like it to stay closer to the higher number and I'm trying to find ways to speed it up.
Would it be faster/better to make(or find?) some mutable subclass of string and work around this problem? Is there another way to solve this issue? Or is this just how it is?
Introduce two new private member variables String renderedScoreString and int rederedScore and rewrite your draw()-method like that:
draw(Canvas c) {
if (this.score != this.renderedScore || this.renderedScoreString == null) {
this.renderedScore = this.score;
this.renderedScoreString = Integer.toString(this.renderedScore);
}
c.drawText(this.renderedScore, x, y, paintStyle);
}
that should save you a lot! of object creations. You could also hide the boilerplate code behind a getter method, e.g. String getScoreString() which does the same, so you don't have it in the draw()-method.
A friend of mine tipped me in on a solution to this problem. When you want to draw something over time, one of the best (and simplest) mechanisms to do so is to split up what you need to do into two completely separate processes.
ie. Only use the draw command exclusively for drawing stuff, keep logic/assignment in Draw() to an absolute minimum.
private final long TIMER_PERIOD = 500;
private String timeString;
private Runnable updateRunnable;
private Handler updateHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
updateRunnable = new Runnable() {
#Override
public void run() {
timeString = GetTimeString();
updateHandler.postDelayed(updateRunnable, TIMER_PERIOD);
}
}
}
Draw(Canvas c) {
c.drawText(timeString, x, y, paintStyle);
}
In this example the Draw command simply takes timeString in its current state and draws it to the screen. This is highly efficient use of the draw function as it does not require any object creation, and no logic is present that is not immediately required for any drawing to occur. . In the background a Runnable is executing the run() function every 500 miliseconds (approximately). Simply update the Run() function with whatever logic you need to calculate the time (example has a dummy function GetTimeString())
I hope this is helpful.
I know I'm resurrecting a dead thread, but there is one extra optimisation you can add to this which restricts String creation to a one-time thing and thus only triggers the GC once at the start and not during the game (which is quite important for an android game).
Somewhere during the start of your game (onCreate, onResume, as part of a singleton during application startup, etc) create a large String[] which can hold the maximum score (my game fills an array of 10000, so the max score would be 9999). Then loop over it with a for loop, filling each index with a String.valueOf(i).
for (int i = 0; i <scoreStrings.length; i++)
{
scoreStrings[i] = String.valueOf(i);
}
Now, when you need to draw the score, just use the int you use to store the score in as an index to that array, and "hey, presto!", you get the correct string for your score.
canvas.drawText(scoreStrings[score], x, y, paint);

Android static method plots background thread data nicely in real-time, but is it a good solution?

I've been asking a series of evolving questions regarding my Android project that continually plots Bluetooth data in real-time. And I haven't done a very good job of asking questions.
So what I need to do is edit this question, clean it up, add important detail, and most importantly I need to add code fragments of relevant sections of code, especially sections I've hacked on quite a bit, and provide explanation about these sections of code. That way maybe I might get an answer to my question/concerns which are: Is my current solution an OK one? Is it going to hold up as I add new features?
Basically what I've already done is create a first version of my app by cobbling together some open source code Blueterm and OrientationSensor.
It's been suggested that I add a thread, a handler, a Service, or use Async Task, or AIDL, etc. But I have decided I don't want to modify or replace my existing solution unless I really should. Mainly I want to know if it's good enough to move forward and extend it to add other features.
By the way what I have previously referred to as BluetoothData is just bluetooth data: it's 16 bit data received from a remote Bluetooth device at the rate of 2 to 10 samples/second. My app is basically a data acquisition system that acquires/receives bluetooth data and plots it.
Here's a description of the Blueterm open source code I started with (see link above). Blueterm is basically a terminal emulator program that communicates over Bluetooth. It consists of several activities with Blueterm being the most important. It discovers, pairs, and connects with a remote Bluetooth device that supports SPP/RfComm. When connected I can use Blueterm to configure the remote device by sending it commands to turn on sampling, change the number of channels to sample (to one channel), change to format of the incoming data (I like comma separated data), etc
Here's a description of the OrientationSensorExample open source code I started with (see link above). It's basically an example application of the AnroidPlot library. The OrientationSensor activity implements SensorEventListener. This includes overriding onSenorChanged() which is called whenever new orientation sensor data is taken, and it redraws the graph.
Having cobbled together these two open source projects (Blueterm and OrientationSensorExample) into one application (Blueterm) here's a description of how the overall application (Blueterm) works. When I start Blueterm the whole screen emulates a nice blue terminal. From the Options Menu I discover, pair with, connect to, and configure a remote bluetooth device as described above. Once I have configured the remote device, I go again to the Options Menu and select "Plot data" which launches the Plot activity. The terminal emulator goes away, and a nice scrolling real-time plot from the Plot activity shows up.
Here's how I did this. In onOptionsItemSelected() I added a case to launch the Plot activity as follows:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.connect:
if (getConnectionState() == BluetoothSerialService.STATE_NONE) {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
else
if (getConnectionState() == BluetoothSerialService.STATE_CONNECTED) {
mSerialService.stop();
mSerialService.start();
}
return true;
case R.id.preferences:
doPreferences();
return true;
case R.id.menu_special_keys:
doDocumentKeys();
return true;
case R.id.plot_data:
doPlotData();
return true;
}
return false;
}
private void doPlotData() {
Intent plot_data = new Intent(this, com.vtrandal.bluesentry.Plot.class);
startActivity(plot_data);
}
Then in the bluetooth background thread I added a call to update() to call plotData() as follows:
/**
* Look for new input from the ptty, send it to the terminal emulator.
*/
private void update() {
int bytesAvailable = mByteQueue.getBytesAvailable();
int bytesToRead = Math.min(bytesAvailable, mReceiveBuffer.length);
try {
int bytesRead = mByteQueue.read(mReceiveBuffer, 0, bytesToRead);
append(mReceiveBuffer, 0, bytesRead);
//VTR use existing handler that calls update() to get data into plotting activity
//OrientationSensor orientationSensor = new OrientationSensor();
Plot.plotData(mReceiveBuffer, 0, bytesRead);
} catch (InterruptedException e) {
//VTR OMG their swallowing this exception
}
}
Then in the Plot activity I basically cleaned house, removed "implements SensorEventListener" and some related methods and variables, and wrote plotData() to be called as shown above. Here's what plotData() and it's helper methods splitData() and nowPlotData() currently look like:
private static StringBuffer strData = new StringBuffer("");
public static void plotData(byte[] buffer, int base, int length) {
Log.i("Entering: ", "plotData()");
/*
byte[] buffer = (byte[]) msg.obj;
int base = msg.arg1;
int length = msg.arg2;
*/
for (int i = 0; i < length; i++) {
byte b = buffer[base + i];
try {
if (true) {
char printableB = (char) b;
if (b < 32 || b > 126) {
printableB = ' ';
}
Log.w("Log_plotData", "'" + Character.toString(printableB)
+ "' (" + Integer.toString(b) + ")");
strData.append(Character.toString(printableB));
if (b == 10)
{
Log.i("End of line: ", "processBlueData()");
Log.i("strData", strData.toString());
splitData(strData);
strData = new StringBuffer("");
}
}
} catch (Exception e) {
Log.e("Log_plotData_exception", "Exception while processing character "
+ Integer.toString(i) + " code "
+ Integer.toString(b), e);
}
}
Log.i("Leaving: ", "plotData()");
}
private static void splitData(StringBuffer strBuf) {
String strDash = strBuf.toString().trim();
String[] strDashSplit = strDash.split("-");
for (int ndx = 0; ndx < strDashSplit.length; ndx++)
{
if (strDashSplit[ndx].length() > 0)
Log.i("strDashSplit", ndx + ":" + strDashSplit[ndx]);
String strComma = strDashSplit[ndx].trim();
String[] strCommaSplit = strComma.split(",");
for (int mdx = 0; mdx < strCommaSplit.length; mdx++)
{
if (strCommaSplit[mdx].length() > 0)
Log.i("strCommaSplit", mdx + ":" + strCommaSplit[mdx]);
if (mdx == 1)
{
int raw = Integer.parseInt(strCommaSplit[1],16);
Log.i("raw", Integer.toString(raw));
float rawFloat = raw;
Log.i("rawFloat", Float.toString(rawFloat));
float ratio = (float) (rawFloat/65535.0);
Log.i("ratio", Float.toString(ratio));
float voltage = (float) (5.0*ratio);
Log.i("voltage", Float.toString(voltage));
nowPlotData(voltage);
}
}
}
}
public static void nowPlotData(float data) {
// get rid the oldest sample in history:
if (plotHistory.size() > HISTORY_SIZE) {
plotHistory.removeFirst();
}
// add the latest history sample:
plotHistory.addLast(data);
// update the plot with the updated history Lists:
plotHistorySeries.setModel(plotHistory, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
//VTR null pointer exception?
if (plotHistoryPlot == null)
Log.i("aprHistoryPlot", "null pointer exception");
// redraw the Plots:
plotHistoryPlot.redraw();
}
Time for a summary: I basically found the update() method in the background thread that was created by the Blueterm activity. The update() method essentially appends newly received bluetooth data to the screen buffer using the append() method. So, the background thread's update() method looked like a good place to call plotPlot(). So I designed plotData() to plot the data being passed to append(). This works as long plotData() is a static method. I would appreciate an explanation as to why plotData() seemingly must be static in order to work.
And again my overall question/concerns: Is my current solution an OK one? Is it going to hold up as I add new features?
I found the method in the background thread that writes BluetoothData to the Logcat. So I am leveraging this method to call a static method, plotData(BluetoothData), in the Plotting Activity. It works nicely plotting the incoming BluetoothData in real-time.
This story does not add up, or BluetoothData is misnamed.
In Android, to plot to the screen, you need an Activity instance, with whatever widget(s) you are plotting on. A plotData() method that does the plotting can be static, but somehow it needs the Activity instance. So, one of the following must be true:
BluetoothData contains an Activity instance (and hence is misnamed), or
plotData() takes more than the one parameter you have indicated, or
you are holding onto an Activity instance in a static data member (BAD BAD BAD BAD BAD), or
plotData() is not a static method, so you are actually calling it on an Activity instance
But, since you repeatedly decline to provide the source code, despite having asked several questions about the code, it is impossible for us to say which of these is really your problem.
Is it not thread safe? Do I have a deadlock issue? Is my solution a fragile one? Am I circumventing the Android OS? Am I lucky that it's working at all? Or is there a proper way to extend the existing design?
The first five of these have different answers depending upon which of the four bullets above reflects reality, and I really do not feel like writing out a 20-cell grid of answers. Your last question assumes that you have actually explained your "design", which you have not.
UPDATE
Some comments based upon the substantial revision to the question:
I would appreciate an explanation as to why plotData() seemingly must be static in order to work.
It probably doesn't have to be static.
Is my current solution an OK one?
Probably not.
Static methods are rarely a problem on their own. Static data is frequently a problem, due to lack of thread safety, memory leaks, and the like. Hence, your objective is to minimize or eliminate all static data members.
There are at least four static data members at play here, perhaps more. One is strData. This isn't too bad, in that you reset the static data member to a fresh StringBuffer on each plotData() call, so your memory leak is modest. However, if plotData() somehow were to be called on multiple threads simultaneously -- and, since I don't know your threading model, that's at least possible -- you will have problems, since you have no synchronization.
However, the far bigger problem is represented by the plotHistory, plotHistorySeries, and plotHistoryPlot static data members are. I have no idea what these objects are. However, by their name and your overall objective, it would appear that redraw() actually draws to the screen, which means that plotHistoryPlot is or holds some subclass of View that is the thing being plotted upon. This means you violated a cardinal rule of Android development:
Never put something that references a transient Context in a static data member
Here, an Activity represents a transient Context, "transient" because activities do go away, Context because it inherits from Context. Your statically-referenced View holds a reference back to its Activity. Hence, this Activity can never be garbage collected, which is bad for business, let alone any possible thread-safety issues.
Again, this is an educated guess, since I don't know what those static data members really are.

Categories

Resources