0

我想SENSOR_ACCELEROMETER在服务中注册一个,但结果是一个空异常。以下是我的代码:

 asensor = new AccerSensor(context);//the sensoreventlistener
 Log.i("wogua", "creating"+asensor.toString());
 manager.registerListener(asensor,manager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);


 Exception:

Caused by: java.lang.NullPointerException::

    at com.wogua.mobileprotected.service.LostProtectService.onCreate(LostProtectService.java:36)

我不知道问题是什么,sensoreventlistener 的实例不是 null::::com.wogua.mobileprotected.sensor.AccerSensor@41bf3f20

这怎么可能是 null,:::manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);

4

2 回答 2

1

这是对我有用的方式:

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

    if (mAccelerometer != null) {
        // Success! There's an accelerometer
        mSensorManager.registerListener(this, mAccelerometer,
                SensorManager.SENSOR_DELAY_FASTEST);
    } else {
        Toast.makeText(this, "This device doesnt support accelerometer",
                Toast.LENGTH_SHORT).show();
        stopSelf();
    }
于 2012-11-23T09:37:46.457 回答
0

manager未初始化,非常确定

于 2012-11-23T10:30:40.873 回答