快速移动的问题(onSensorChanged + Timer)

时间:2012-05-06 15:28:24

标签: android timer accelerometer sensor tilt

我正在尝试制作一些Android应用程序,它会在抖动时更改TextView文本(使用X轴上的onSensorChanged)。 Shake实际上是在很短的时间内移动。 看起来我的快速移动捕捉器代码部分工作完美,因为应用程序崩溃摇晃,但它不是我想要的:)。看起来像那个部分的问题,它改变了TextView文本,但我看不出错误。这是我的代码,谢谢你的帮助!

public class TheoryActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;

TextView xCoor;
TextView event;

static float oldx = 0;
static float curx = 0;


@Override
public void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    xCoor=(TextView)findViewById(R.id.xcoor);
    event =(TextView)findViewById(R.id.event);

    sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
    sensorManager.registerListener(this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);
}

public void onAccuracyChanged(Sensor sensor,int accuracy){

}

public void onSensorChanged(SensorEvent event){

    if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){

        float x=event.values[0];
        xCoor.setText("X: "+x); //Getting phone position and set in    TextView  
        curx = x; 

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTime(), 1, 500); //Here's timer to make that small range of time for move
    }
}


private class MyTime extends TimerTask {

    @Override
    public void run() {
            if(Math.abs(curx - oldx) > 6) //Check if phone has been moved for 6 point in any way
            {
                event.setText("Boom!"); //Here's some test event to see result of whole code, but here it crashes. Without this line app works fine
            }
                    oldx = curx;
    }

    }

}

0 个答案:

没有答案