Android Wear应用程序在注册传感器监听器时崩溃



我正在尝试为Android Wear创建一个计步器应用程序。我的问题是当我注册一个传感器监听器

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

应用程序崩溃但如果我删除上面的代码应用程序工作,但诅咒的传感器监听器不工作所以我怎么能使它工作,这里是代码

public class WearMainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepDetectorSensor;
TextView stepNum;
int steps = 12;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wear_main);
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            stepNum = (TextView) findViewById((R.id.stepNum));
            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);


        }
    });



}
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mStepDetectorSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
        stepNum.setText(String.valueOf(steps));
    }
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

protected void onStop() {
    super.onStop();
    mSensorManager.unregisterListener(this,mStepDetectorSensor);
}
}

你应该在onResume方法中声明这两个变量:

protected void onResume() {
    super.onResume();
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
    mSensorManager.registerListener(this, mStepDetectorSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

和取消注册传感器在onPause

相关内容

  • 没有找到相关文章

最新更新