user3483163
user3483163

Reputation: 45

How to use Android's Accelerometer

I used this Accelerometer guide for android screen movement. I am confused about all the calculations and the significance of the x, y, z values. What does a z=-.60 signify? or a y=8.4253?

Ultimately, I would like to know how to get a value to see how much they are moving the screen left-to-right or in the X-axis because I want to make a bitmap/image on the screen move left if the screen is tilted/moved left and it move right if the screen is tilted right.

I do not know the algorithm for that nor do I know what the values mean so any feedback or guidance upon this information would be most beneficial.

Upvotes: 0

Views: 153

Answers (1)

Hong Thai
Hong Thai

Reputation: 218

Your Activity can implement SensorEventListener, override onSensorChanged(SensorEvent event) like this:

public void onSensorChanged(SensorEvent event) {
    float x = event.values[0];
    float y = event.values[1];
    if (Math.abs(x) > Math.abs(y)) {
        if (x < 0) {
            image.setImageResource(R.drawable.right);
            textView.setText("You tilt the device right");
        }
        if (x > 0) {
            image.setImageResource(R.drawable.left);
            textView.setText("You tilt the device left");
        }
    } else {
        if (y < 0) {
            image.setImageResource(R.drawable.up);
            textView.setText("You tilt the device up");
        }
        if (y > 0) {
            image.setImageResource(R.drawable.down);
            textView.setText("You tilt the device down");
        }
    }
    if (x > (-2) && x < (2) && y > (-2) && y < (2)) {
        image.setImageResource(R.drawable.center);
        textView.setText("Not tilt device");
    }
}

More details, see my full post at: http://www.devexchanges.info/2015/05/detecting-tilt-device-by-using-sensor.html

Upvotes: 1

Related Questions