我好几天都在寻找答案而且找不到任何答案。
问题是,我制作了一个非常简单的Android应用来计算步数。它适用于索尼和LG设备,但不适用于摩托罗拉设备(试用过第二代和第三代Moto X)。
我得到“传感器或监听器为空”的消息。
这是我的代码,任何帮助将不胜感激。谢谢!
package com.xxx.yyy;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager.getDefaultSensor(19,true);
// mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_FASTEST);
// mSensorManager.registerListener(this, mStepDetectorSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
// mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("Step Counter Detected : " + value);
} else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
// For test only. Only allowed value is 1.0 i.e. for step taken
// textView.setText("Step Detector Detected : " + value);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}