3

I want to listen to a shake and then stop the accelerometer completely and move to another activity. Sadly I didn't find any way to do this. Even if I count up a variable and check with a simple 'if' it loads always the new activity again every time a shake is detected.

Please help me with my lack of understanding.

@Override
  protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    mSensorManager.unregisterListener(mSensorListener);
    super.onPause();

  }

  @Override
  protected void onStop() {
    mSensorManager.unregisterListener(mSensorListener);
    super.onStop();
  }




private SensorManager mSensorManager;

  private final SensorEventListener mSensorListener = new SensorEventListener() {


@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
    // TODO Auto-generated method stub

}




@Override
public void onSensorChanged(SensorEvent event) {


    float[] value = event.values;



    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = value[0];
            float y = value[1];
            float z = value[2];


            //in G Umrechnung
            float gX = x / gravityEarth;
            float gY = y / gravityEarth;
            float gZ = z / gravityEarth;

          //G-Force will be 1 when there is no movement. (gravity)
             gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ);

             double gForce2 = Math.round(gForce * 100) / 100.0;

             String g = String.format("" + gForce2 + " G");
             TextViewG.setTextColor(0xffff0000);
             TextViewG.setTextSize(35);
             TextViewG.setText(g);

    }


    Intent nextScreen = new Intent(getApplicationContext(), Send.class);

    if (gForce > shakeThresholdInGForce ){


        final long now = System.currentTimeMillis();

        // ignore shake events too close to each other (500ms)
        if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now ) {

            mShakeTimestamp = now;



                   mSensorManager.unregisterListener(mSensorListener);
            onStop();




            startActivity(nextScreen);



        }

    }
Saju
  • 3,201
  • 2
  • 23
  • 28
bastifix
  • 443
  • 1
  • 6
  • 18
  • I have implemented a similar functionality. All I had was having the sensor manager to unregister the listener on Stop and it works well. I'd believe there's a problem somewhere else in your code. – Ryan Huang Jan 29 '13 at 00:20
  • what is your for "shakeThresholdInGForce " ? – nayab Jan 30 '13 at 15:50

0 Answers0