Feeds:
Posts
Comments

Posts Tagged ‘service’

A friend of mine tested the sleep-cycle application on iPhone and I wanted to test it myself, a quick search for applications for Android yielded some results but I thought I could make my own a prototype in a couple of hours and learn something in the process.

I wanted my application to register movements of the phone using the accelerometer, the phone itself would lie on the bed and register when I turned in my sleep. A high number of turns would then register as uneasy sleep. This is a prime example of implementing a Service (like MyTracks and the music player) that can run in the background even if the phone has gone in stand-by.

Basic bits of reading from the accelerometer

// Pseudo code ... showing the interesting bits.

public class MyService extends Service implements SensorEventListener {

// Obtain a reference to system-wide sensor event manager.
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

// Register for events.
mSensorManager.registerListener(
  this,
  mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
  SensorManager.SENSOR_DELAY_NORMAL);

public void onSensorChanged(SensorEvent event) {
		mNewValue = (int) event.values[0]*10;

		if (mNewValue != mOldValue) {
			Log.d(TAG, Integer.toString(mNewValue));
			mOldValue = mNewValue;
			SystemClock.sleep(1000);
		}
	}

This above could worked together with an Activity that started the Service and that would handle the data, right now it just showed the result in the log. I also did a convert from the float because even if the phone would lie still I’d get very small changes all the time that would trigger the reading. This would of course be calibrated later on.

Everything worked fine, but the instance the phone went into standby readings would stop. This seemed strange since the GPS can be read even when in sleep mode, some googling later I found out that this was a well known issue and can be read about here: LINK

There was a some hacks that might get it working by listening for the broadcast that the phone went into standby, and re-register the SensorEventListener, I made the changes but it doesn’t work on my HTC Legend (2.1). From what I’ve gathered this work around only functions on the Motorola Droid/Milestone. I guess they have implemented this to save battery but it could easily be fixed by having a permission “Application can read sensors, when the phone is in standby (will lower battery time)”. But if you want to read the accelerometer in stand-by the only way of handling this is having a wake-lock, but that would mean having the phone’s screen on the whole night and I don’t think most phones can handle that without depleting their battery.

Read Full Post »