package zhangphil.sensor;
import android.content.Context;
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.util.Log;
public class MainActivity extends AppCompatActivity {
private String TAG = "ZHANG PHIL";
private SensorManager mSensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startSensor();
}
/**
* 启动传感器。
*/
private void startSensor() {
mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
Sensor mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
Sensor mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
if (mSensorManager == null || mStepCounterSensor == null || mStepDetectorSensor == null) {
throw new UnsupportedOperationException("设备不支持");
}
mSensorManager.registerListener(mSensorEventListener, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(mSensorEventListener, mStepDetectorSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private SensorEventListener mSensorEventListener = new SensorEventListener() {
private float step, stepDetector;
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
/**
* 计步计数传感器传回的历史累积总步数
*/
if (sensorEvent.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
step = sensorEvent.values[0];
Log.d(TAG, "STEP_COUNTER:" + step);
}
/**
* 计步检测传感器检测到的步行动作是否有效?
*/
if (sensorEvent.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
stepDetector = sensorEvent.values[0];
Log.d(TAG, "STEP_DETECTOR:" + stepDetector);
if (stepDetector == 1.0) {
Log.d(TAG, "一次有效的步行");
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mSensorManager.unregisterListener(mSensorEventListener);
}
}