Tuesday, February 2, 2010

Android Detect Sleep Movement

Follow up from: http://jvyloh.blogspot.com/2009/07/record-sleep-cycle-using-android.html

There are enquiries / requests for the app / source code. I am posting some code snippets to help you get started implementing a better Sleep Cycle Detector. You are welcome to comment on it and suggest improvement. Kindly post me a link to your better app so I can try it out :-)

Well, I have no plan to publish the app as I am busy on other projects, it remains as a proof-of-concept. There are similar apps in the Android Market, one of them is by Alexander Kosenkov called Smart Alarm Clock for Android.

I also found some other code example here: http://www.clingmarks.com/?p=25

Code snippets:

1. Get the 'Sensor Service', e.g.:
SensorManager senMgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);

2. Register Sensor Listener, and set how often you like to receive events, e.g.:
senMgr.registerListener(sensorEvtLsnr, sensor, SensorManager.SENSOR_DELAY_NORMAL);

3. Create the Sensor Listener, e.g.:
private SensorEventListener sensorEvtLsnr = new SensorEventListener()
{
//your code here
};

4. Override the method that receive the sensor events:
private SensorEventListener sensorEvtLsnr = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent evt)
{
//your code here
}
};

5. Listen to the type sensor event you interested, in this case:
  • Sensor.TYPE_ACCELEROMETER
There are other sensor type which are applicable for different application:
  • Sensor.TYPE_MAGNETIC_FIELD
  • Sensor.TYPE_ORIENTATION
6. Implement your algorithm what you consider a movement, for my simple POC, I monitor the change in the ACCELEROMETER X value, a change of value to consider a movement count, and I have a timer that gathers the number of movement count per minute, which you can use to plot a graph, persist to a file or post to the cloud.

int cAccX, //movement count per minute
float accX; //accelerometer x value
TextView tvAccelerometer; //TextView to show display data on screen

private SensorEventListener sensorEvtLsnr = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent evt)
{
if(evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER ){
if(accX != evt.values[0]){
accX = evt.values[0];
cAccX++;
tvAccelerometer.setText("Accelerometer[x] = " + cAccX + " = " + accX );
}
}
}
};



0 comments: