Pedometer, SensorListener is null

时间:2016-04-04 16:50:43

标签: android

So I am doing a project for a class with an Android where we use the virtual sensor pedometer but we have this error : " SensorListener is null".

private SensorManager mSensorManager;
private Sensor stepDetector;
private Sensor accelerometer;
private Sensor magnetometer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_step_monitor);



    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    stepDetector = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR); 
    accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, stepDetector, SensorManager.SENSOR_DELAY_FASTEST); // problem
    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
    mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
}

protected void onPause() {
    super.onPause();

    mSensorManager.unregisterListener(this);
}

1 个答案:

答案 0 :(得分:2)

Could you share your code where you have initialized stepDetector, accelerometer, magnetometer ?

Some basic key points are:

1) Your class must implement SensorEventListener and all its methods:

public class myClass implements SensorEventListener{ }

2) Then you must initialize the sensors you want to use as follows:

SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)

3) Register the sensor as follows:

if(accelerometer!=null){
    mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
} //you will get the sensor as null if phone does not have it

4) And lastly use this for unregistering:

mSensorManager.unregisterListener(this, accelerometer);

Hope this helps