I'm creating an app that makes use of accelerometer data to calculate device roll and pitch.
This is what I have for now, still haven't coded the roll/pitch calculations.
Just checking to see which sensors are present and listing them in logcat, checking if device has accelerometer, and implementing a simple output GUI (4 textviews, corresponding to the 3 axes and max sensor range).
X and Y read correctly with phone stationary and rotating along one axys at a time, and go from 0 to around 9.5 (which would correspond to the normal 9.8m/s2 corresponding to earth's gravity force). Shaking the device results in values going over the 9.8 threshold, as expected.
Z acceleration (sensorEvent.values[2]), however, is stationary at around 0.032 (lets call it a zero). Shaking, rotating, everything short of throwing it against a wall produces absolutely no change... Which renders any of my attempts to calculate roll and pitch pretty much useless...
Is there anything wrong with this code, or should I assume something is wrong with this particular phone (tested it with my wife's phone which is exactly the same model: same results).
Accelerometer is a KXTJ2-1009 3-axis Accelerometer (its the phones
only physical sensor)
Phone is a chinese-made HTM phone (suppose its a HTC clone)
(http://www.everbuying.com/product555984.html)
public class MainActivity extends ActionBarActivity implements SensorEventListener {
private TextView raw_x, raw_y, raw_z, acc_max;
private boolean hasAccelerometer;
private SensorManager senSensorManager;
private Sensor senAccelerometer;
private long lastUpdate = 0;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 700;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sMgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
String data = new String();
for (Sensor sensor : list) {
data += (sensor.getName() + "\n");
data += (sensor.getVendor() + "\n");
data += (sensor.getVersion() + "\n");
}
Log.d(TAG, data);
PackageManager manager = getPackageManager();
hasAccelerometer = manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);
if(hasAccelerometer) {
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
}
Log.d(TAG,Float.toString(senAccelerometer.getMaximumRange()));
initGui();
}
#Override
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
float x = (float) sensorEvent.values[0];
float y = (float) sensorEvent.values[1];
float z = (float) sensorEvent.values[2];
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
float speed = Math.abs(x + y + z - last_x - last_y - last_z)/ diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
//doSomething()
}
if(raw_x!=null){
raw_x.setText(Float.toString(x));
raw_y.setText(Float.toString(y));
raw_z.setText(Float.toString(z));
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void initGui() {
setContentView(R.layout.activity_main);
raw_x = (TextView) findViewById(R.id.lbl_raw_x);
raw_y = (TextView) findViewById(R.id.lbl_raw_y);
raw_z = (TextView) findViewById(R.id.lbl_raw_z);
acc_max = (TextView) findViewById(R.id.lbl_max);
acc_max.setText(Float.toString(senAccelerometer.getMaximumRange()));
}
}
Apparently this is normal, since Z-axis depends on magnetic orientation. Without a gyroscope, magnetometer or compass the z-value will most likely always be 0. Or at least remain unchanged.
Since this phone of mine has none of those, that clears it up.
Related
I have made android app that plays next song when shake once using Accelerometer.
Now what i want my in app if a shake the phone in right side it should play the next song in line or if shake in left play previous, can i do it with the logic of axis found at time of shake action if that is possible
how can I put axis to the methods of motion detection to know the direction in which the mobile is shaked. If any one have a logic for this please help i am stuck here.
I did some digging into this and was able to resolve it myself. but while posting the answer I found this answer by Basil which explains better than my implementation. So, i found it more helpful.
what he did
In the onSensorChanged whenever the device receives new value it store the values into variables after some delay. After that compares the new value with previous values beautifully. Which leads to calculate into direction the device has shakes. If the answer is still unclear let me know.
public class ShakeActivity extends Activity implements SensorListener {
// For shake motion detection.
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 800;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// start motion detection
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
}
}
protected void onPause() {
if (sensorMgr != null) {
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
sensorMgr = null;
}
super.onPause();
}
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(int sensor, float[] values) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
x = values[SensorManager.DATA_X];
y = values[SensorManager.DATA_Y];
z = values[SensorManager.DATA_Z];
if(Round(x,4)>10.0000){
Log.d("sensor", "X Right axis: " + x);
Toast.makeText(this, "Right shake detected", Toast.LENGTH_SHORT).show();
}
else if(Round(x,4)<-10.0000){
Log.d("sensor", "X Left axis: " + x);
Toast.makeText(this, "Left shake detected", Toast.LENGTH_SHORT).show();
}
float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
// Log.d("sensor", "diff: " + diffTime + " - speed: " + speed);
if (speed > SHAKE_THRESHOLD) {
//Log.d("sensor", "shake detected w/ speed: " + speed);
//Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
}
I wrote the following code,where the values of the accelerometer are shown in x,y,z during rotation.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView xText,yText,zText;
private Sensor mySensor;
private SensorManager SM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the Sensor Manager
SM = (SensorManager)getSystemService(SENSOR_SERVICE);
// Accelerometer Sensor
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// Register sensor Listener
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
// Assign TextView
xText = (TextView)findViewById(R.id.xText);
yText = (TextView)findViewById(R.id.yText);
zText = (TextView)findViewById(R.id.zText);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
xText.setText("X: " + sensorEvent.values[0]);
yText.setText("Y: " + sensorEvent.values[1]);
zText.setText("Z: " + sensorEvent.values[2]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
Now I want to convert the values I get from the SensorEvents to degrees. I looked at various questions here,but I got confused.
double x = sensorEvent.values[0];
double y = sensorEvent.values[1];
double z = sensorEvent.values[2];
There should be a formula that takes the above values and convert them in degrees.
Any ideas?
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
//xText.setText("X: " + sensorEvent.values[0]);
//yText.setText("Y: " + sensorEvent.values[1]);
//zText.setText("Z: " + sensorEvent.values[2]);
double x = sensorEvent.values[0];
double y = sensorEvent.values[1];
double z = sensorEvent.values[2];
double pitch = Math.atan(x/Math.sqrt(Math.pow(y,2) + Math.pow(z,2)));
double roll = Math.atan(y/Math.sqrt(Math.pow(x,2) + Math.pow(z,2)));
//convert radians into degrees
pitch = pitch * (180.0/3.14);
roll = roll * (180.0/3.14) ;
yText.setText(String.valueOf(pitch));
zText.setText(String.valueOf(roll));
}
Now I want to convert the values I get from the SensorEvents to degrees
The unit of the value you get from TYPE_ACCELEROMETER is m/s^2, thus trying to convert to degree does not make sense.
Your pitch and roll calculations do not seem right. For the correct calculation see the method processSensorData(DProcessedSensorEvent.DProcessedSensorEventBuilder builder) in the DSensorEventProcessor class at https://github.com/hoananguyen/dsensor/blob/master/dsensor/src/main/java/com/hoan/dsensor_master/DSensorEventProcessor.java
To convert pitch and roll to degrees use Math.toDegrees(valueToConvert)
Youll need to register for the TYPE_ACCELEROMETER, but also for TYPE_MAGNETIC_FIELD and than you can leverage SensorManager built-in method for your help:
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
gravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
geomagnetic = event.values;
if (mGravity != null && geomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
myAzimut = orientation[0]; // myAzimut is The geomagnetic inclination angle in radians.
}
}
}
You can learn all additional information by reading SensorManagersource code comments.
your code seem right. use Math.PI in (180.0/3.14) to get more accurate results.
My question is, when i shaking android device i would like to calculate the velocity of android device. I tried, but failed. By using accelerometer sensors based on android api need to calculate the velocity. Here i have x,y,z axis values based on that i have acceleration convert those in to velocity and updating the velocity in each and every second, but no use. Am obtaining please go through the below code and provide solution where i went wrong.
public class Speedometer extends Activity {
Handler handler = new Handler();
SensorManager sensorManager;
TextView myTextView,tv1_x,tv2_y,tv3_z,tv5;
float appliedAcceleration = 0;
float currentAcceleration = 0;
float velocity = 0;
Date lastUpdate;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTextView = (TextView)findViewById(R.id.myTextView);
tv1_x=(TextView)findViewById(R.id.textView1);
tv2_y=(TextView)findViewById(R.id.textView2);
tv3_z=(TextView)findViewById(R.id.textView3);
tv5=(TextView)findViewById(R.id.textView5);
lastUpdate = new Date(System.currentTimeMillis());
Log.i("TIME", ""+lastUpdate);
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(sensorEventListener,
accelerometer,
SensorManager.SENSOR_DELAY_UI);
Timer updateTimer = new Timer("velocityUpdate");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 1000);
}
private void updateGUI() {
// Convert from meters per second to miles per hour.
final double V_mph = (Math.round(100*velocity / 1.6 * 3.6))/100;
// Update the GUI
handler.post(new Runnable() {
public void run() {
myTextView.setText(String.valueOf(V_mph) + "mph");
//tv5.setText(String.valueOf(distance_val));
}
});
}
private void updateVelocity() {
// Calculate how long this acceleration has been applied.
Date timeNow = new Date(System.currentTimeMillis());
Log.i("TIME_now", ""+timeNow);
long timeDelta = timeNow.getTime()-lastUpdate.getTime();
lastUpdate.setTime(timeNow.getTime());
Log.i("last update time TIME", ""+lastUpdate);
// Calculate the change in velocity at the
// current acceleration since the last update.
appliedAcceleration = currentAcceleration;
float deltaVelocity = appliedAcceleration * (timeDelta/1000);
// Add the velocity change to the current velocity.
velocity += deltaVelocity;
Log.i("last update time velocity", ""+velocity);
}
//private final SensorListener sensorListener = new SensorListener() {
private final SensorEventListener sensorEventListener = new SensorEventListener() {
double calibration = Double.NaN;
public void onSensorChanged(SensorEvent event) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
tv1_x.setText(""+x);
tv2_y.setText(""+y);
tv3_z.setText(""+z);
double a = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
Log.i("TIME_in sensor", "Double val a"+a);
if (calibration == Double.NaN)
calibration = a;
else {
updateVelocity();
currentAcceleration = (float)a;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
};
}
provide solution to update velocity on the device screen each and every second.
Thanks in advance.
I need suggestion about how to detect the amount of movement of an android device. Suppose I have put the phone on a table or bed and then if somebody taps the table or sits or laydown on the bed then I want to detect the movement of the android device.
Actually I know that android has motion sensors APIs but I don't know which sensor to use and what sensor type is best for this type of movement detection.
I would be glad if someone can share some basic demo code.
Definitely work with the accelerometer:
// Start with some variables
private SensorManager sensorMan;
private Sensor accelerometer;
private float[] mGravity;
private float mAccel;
private float mAccelCurrent;
private float mAccelLast;
// In onCreate method
sensorMan = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
// And these:
#Override
public void onResume() {
super.onResume();
sensorMan.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
super.onPause();
sensorMan.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
mGravity = event.values.clone();
// Shake detection
float x = mGravity[0];
float y = mGravity[1];
float z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = FloatMath.sqrt(x*x + y*y + z*z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
// Make this higher or lower according to how much
// motion you want to detect
if(mAccel > 3){
// do something
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// required method
}
I used the following class:
public class MovementDetector implements SensorEventListener {
protected final String TAG = getClass().getSimpleName();
private SensorManager sensorMan;
private Sensor accelerometer;
private MovementDetector() {
}
private static MovementDetector mInstance;
public static MovementDetector getInstance() {
if (mInstance == null) {
mInstance = new MovementDetector();
mInstance.init();
}
return mInstance;
}
//////////////////////
private HashSet<Listener> mListeners = new HashSet<MovementDetector.Listener>();
private void init() {
sensorMan = (SensorManager) GlobalData.getInstance().getContext().getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorMan.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
}
public void start() {
sensorMan.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void stop() {
sensorMan.unregisterListener(this);
}
public void addListener(Listener listener) {
mListeners.add(listener);
}
/* (non-Javadoc)
* #see android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent)
*/
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float diff = (float) Math.sqrt(x * x + y * y + z * z);
if (diff > 0.5) // 0.5 is a threshold, you can test it and change it
Log.d(TAG,"Device motion detected!!!!");
for (Listener listener : mListeners) {
listener.onMotionDetected(event, diff);
}
}
}
/* (non-Javadoc)
* #see android.hardware.SensorEventListener#onAccuracyChanged(android.hardware.Sensor, int)
*/
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public interface Listener {
void onMotionDetected(SensorEvent event, float acceleration);
}
}
Usage:
On my activity onCrate():
MovementDetector.getInstance().addListener(new MovementDetector.Listener() {
#Override
public void onMotionDetected(SensorEvent event, float acceleration) {
mMotionDetectionTextView.setText("Acceleration: ["+String.format("%.3f",event.values[0])+","+String.format("%.3f",event.values[1])+","+String.format("%.3f",event.values[2])+"] "+String.format("%.3f", acceleration));
if (acceleration > SettingsHelper.getInstance().getMotionDetectionThreshold()){
mMotionDetectionTextView.setTextColor(Color.RED);
} else {
mMotionDetectionTextView.setTextColor(Color.WHITE);
}
}
});
On my activity onResume():
MovementDetector.getInstance().start();
On my activity onPause():
MovementDetector.getInstance().stop();
This code is for walking detection (Modified from #anthropomo code)
to get smoother value.
// initialize
private SensorManager sensorMan;
private Sensor accelerometer;
private float[] mGravity;
private double mAccel;
private double mAccelCurrent;
private double mAccelLast;
private boolean sensorRegistered = false;
// onCreate
sensorMan = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
sensorMan.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
sensorRegistered = true;
// onSensorChanged
private int hitCount = 0;
private double hitSum = 0;
private double hitResult = 0;
private final int SAMPLE_SIZE = 50; // change this sample size as you want, higher is more precise but slow measure.
private final double THRESHOLD = 0.2; // change this threshold as you want, higher is more spike movement
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity = event.values.clone();
// Shake detection
double x = mGravity[0];
double y = mGravity[1];
double z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = Math.sqrt(x * x + y * y + z * z);
double delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
if (hitCount <= SAMPLE_SIZE) {
hitCount++;
hitSum += Math.abs(mAccel);
} else {
hitResult = hitSum / SAMPLE_SIZE;
Log.d(TAG, String.valueOf(hitResult));
if (hitResult > THRESHOLD) {
Log.d(TAG, "Walking");
} else {
Log.d(TAG, "Stop Walking");
}
hitCount = 0;
hitSum = 0;
hitResult = 0;
}
}
}
I have been working with a similar idea to measure the displacement of the phone. I have found that the LINEAR ACCELERATION (and ACCELERATION) are not accurate enough to correctly measure the displacement.
This code should work a little better:
(ititialize)
private SensorManager sensorManager;
private Sensor accelerometer;
double[] maxAccelerations = new double[3];
double[] position = new double[3];
long[] times = new long[3];
// time combined with maxAcceleration can approximate the change in position,
// with the formula Δpos = (maxAcceleration * time ^ 2) / 6
long currentTime;
(onCreate)
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION) != null) {
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorManager.registerListener(this, accelerometer, sensorManager.SENSOR_DELAY_FASTEST);
}
currentTime = System.currentTimeMillis();
for(int i=0;i<3;i++){
times[i]=currentTime;
}
else{
throw "Error";
//Which will throw an error, if not the error that is expected. 😉
}
(onSensorChanged and onAccuracyChanged)
#Override
public void onAccuracyChanged(Sensor ignore, int thisFunction) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
for(int i=0;i<3;i++){
if(Math.abs(event.values[i])<0.01){
// Note: this is to try to prevent accelerating time from being counted when the phone is stationary. 0.01 should be
// changed to an appropriate sensitivity level that can be calculated by finding an average noise level when the phone is stationary.
times[i]=System.currentTimeMillis();
}
if(event.values[i]>maxAccelerations[i] && maxAccelerations[i]>=0){
maxAccelerations[i]=event.values[i];
}
else if(event.values[i]<maxAccelerations[i] && maxAccelerations[i]<=0){
maxAccelerations[i]=event.values[i];
}
else if(event.values[i]>0 && maxAccelerations[i]<0){
currentTime = System.currentTimeMillis();
position[i]+=maxAccelerations[i] * (times[i]-currentTime)*(times[i]-currentTime) / 6;
times[i]=currentTime;
maxAccelerations[i]=event.values[i];
}
else if(event.values[i]<0 && maxAccelerations[i]>0){
currentTime = System.currentTimeMillis();
position[i]+=maxAccelerations[i] * (times[i]-currentTime)*(times[i]-currentTime) / 6;
times[i]=currentTime;
maxAccelerations[i]=event.values[i];
}
}
}
}
While I don't have demo code (since you aren't specific enough), a good start is here: http://developer.android.com/guide/topics/sensors/sensors_motion.html (and other items on the left).
if you are trying to find the displacement of your phone, you need to find the
Linear acceleration acting on your phone rather than the acceleration due to gravity
android has a built in converter to find the LINEAR ACCELERATION acting on your mobile phone
https://github.com/yuvaramsingh94/AndroidSensorTestCode/tree/master
this is a code where you can see how to get the raw value of LINEAR ACCELERATION
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android: I want to shake it!
How to use Accelerometer to measure distance for Android Application Development
How to Implement SensorListener?
If Device is not Shaking at that time the Alertdialog is Displayed so how to get the device is shaking or not?
Use this code for check device is shake or not
// Need to implement SensorListener
public class ShakeActivity extends Activity implements SensorListener {
// For shake motion detection.
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 800;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...... // other initializations
// start motion detection
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
}
}
protected void onPause() {
if (sensorMgr != null) {
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
sensorMgr = null;
}
super.onPause();
}
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(int sensor, float[] values) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
x = values[SensorManager.DATA_X];
y = values[SensorManager.DATA_Y];
z = values[SensorManager.DATA_Z];
float speed = Math.abs(x+y+z - last_x - last_y - last_z)
/ diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
// yes, this is a shake action! Do something about it!
// if device is shake with threshold then this condition become true..
// you can put your code here...
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
}