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 SensorManager mSensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startSensor();
}
/**
* 启动传感器。
*/
private void startSensor() {
mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if (mSensorManager == null || mSensor == null) {
throw new UnsupportedOperationException("设备不支持");
}
boolean isRegister = mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
if (!isRegister) {
throw new UnsupportedOperationException();
}
}
private SensorEventListener mSensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_PRESSURE) {
/**
* 传感器返回的压强,单位是百帕。
*/
float pressure = sensorEvent.values[0];
Log.d("压强", String.valueOf(pressure) + "百帕");
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mSensorManager.unregisterListener(mSensorEventListener);
}
}