Created
March 20, 2012 18:01
-
-
Save iewnait/2138807 to your computer and use it in GitHub Desktop.
onSensorChanged() for accelerometer demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
public void onSensorChanged(SensorEvent event) { | |
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { | |
if (isShakeDetected(event)) { | |
// If we detected a shake, update to the next background color. | |
mBackgroundColorIndex = (mBackgroundColorIndex + 1) % mBackgroundColorArray.length; | |
mTargetView.setBackgroundColor(mBackgroundColorArray[mBackgroundColorIndex]); | |
} | |
} | |
} | |
/* | |
* This function determines whether the accelerometer detected a force of | |
* greater than SHAKE_FORCE_THRESHOLD_IN_G, which we will consider to be a shake. | |
* For details of the information returned by the accelerometer and how to use it, | |
* please see the android documentation at: | |
* http://developer.android.com/guide/topics/sensors/sensors_motion.html | |
* | |
*/ | |
private boolean isShakeDetected(SensorEvent event){ | |
float[] values = event.values; | |
float x = values[0]; | |
float y = values[1]; | |
float z = values[2]; | |
float numberOfGsDetected = (x * x + y * y + z * z) | |
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH); | |
if (numberOfGsDetected >= SHAKE_FORCE_THRESHOLD_IN_G) | |
{ | |
long currentMs = System.currentTimeMillis(); | |
if ((currentMs - mLastUpdateMs) > MAX_COLOR_CHANGE_FREQUENCEY_MS) { | |
mLastUpdateMs = currentMs; | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment