I created a class for accelerometer, and there are no errors, my game does not crash when I run it, but my character does not move when I tilt my phone. I have been trying to figure out how to use the accelerometer for some days now, but every tutorial uses it in an activity, and there is no activity in my application.

Here is the code:

package com.saladchef.bananasplit;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class MyAccelerometerClass implements SensorEventListener {
private SensorManager sensorManager;

public float x, y, z;

public MyAccelerometerClass(Context context) {
    sensorManager = (SensorManager) context

public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub


public void onSensorChanged(SensorEvent event) {
    x = event.values[0];
    y = event.values[1];
    z = event.values[2];

    if (y == 0.0){
    if(y >= 1.5){

    if (y <= -1.5){


public SensorManager getSensorManager() {
    return sensorManager;

public void setSensorManager(SensorManager sensorManager) {
    this.sensorManager = sensorManager;

public float getX() {
    return x;

public void setX(float x) {
    this.x = x;

public float getY() {
    return y;

public void setY(float y) {
    this.y = y;

public float getZ() {
    return z;

public void setZ(float z) {
    this.z = z;

// codes


  • \$\begingroup\$ I just want to point out that the accelerometer orientations is set up with the devices default orientation and does not change as the device is rotated. That is, phone default orientation is usually portrait, and tablets is usually landscape. If not handled properly your character might be moving up and down instead of left and right on some devices. \$\endgroup\$ – Aholio Aug 7 '14 at 0:43

You need to register listener and get sensor, see official site.

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

  protected void onResume() {
    mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);

  protected void onPause() {
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.