In my latest android game WordWrench I detect the "shaking" motion of the phone as follows (the following is pseudo code, I did not try to compile it)
MyActivity.java
Using java Syntax Highlighting
- public class MyActivity extends Activity
- {
- private MyView m_myView;
- private SensorManager m_sensorManager;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- m_myView = (MyView)findViewById(R.id.my_view);
- m_sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
- m_sensorManager.registerListener(m_myView,
- SensorManager.SENSOR_ACCELEROMETER,
- SensorManager.SENSOR_DELAY_GAME);
- }
- @Override
- protected void onPause()
- {
- super.onPause();
- m_sensorManager.unregisterListener(m_myView);
- }
- @Override
- protected void onResume()
- {
- super.onResume();
- m_sensorManager.registerListener(m_myView,
- SensorManager.SENSOR_ACCELEROMETER,
- SensorManager.SENSOR_DELAY_GAME;
- }
- }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
MyView.java
Using java Syntax Highlighting
- public class MyView extends View implements SensorListener
- {
- private float m_totalForcePrev; // stores the previous total force value
- // do your constructor and all other important stuff here
- // make sure you set totalForcePrev to 0
- // ...
- public void onAccuracyChanged(int arg0, int arg1)
- {
- // I have no desire to deal with the accuracy events
- }
- public void onSensorChanged(int sensor, float[] values)
- {
- if(sensor == SensorManager.SENSOR_ACCELEROMETER)
- {
- double forceThreshHold = 1.5f;
- double totalForce = 0.0f;
- totalForce += Math.pow(values[SensorManager.DATA_X]/SensorManager.GRAVITY_EARTH, 2.0);
- totalForce += Math.pow(values[SensorManager.DATA_Y]/SensorManager.GRAVITY_EARTH, 2.0);
- totalForce += Math.pow(values[SensorManager.DATA_Z]/SensorManager.GRAVITY_EARTH, 2.0);
- totalForce = Math.sqrt(totalForce);
- if((m_gameState == STATE_RUNNING) && (totalForce < forceThreshHold) && (m_totalForcePrev > forceThreshHold))
- {
- doWrenchWord();
- }
- m_totalForcePrev = totalForce;
- }
- }
- }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
Feel free to let me know what you think of it o rif you have a different strategy when detecting the "shake" of hte device.
*EDIT*
I figured out the problem on my own... so this is just an example post now. @Mods: feel free to move it to a different sub forum if you want
[color=red][mod]I will, as this is now a Code Snippet
. Moved[/mod]*EDIT #2*
thanks to this thread on the android developers group I was reminded of some of my old physics classes and I was able to simplify the coding of this function and also was able to get better overall result
android develoeprs



