我正在玩传感器,看看我能用它做什么,所以第一步是获取传感器数据。然而,除了加速度计之外,甚至任何传感器都可以获得多个传感器。因为这是我手机上收到的唯一数据。
我试图用加速计关闭它来运行它,但不管其他感觉器都没有显示它们的数据。
public class MainActivity extends AppCompatActivity implements SensorEventListener {
//TODO: Database variables
//Backend variables
private SensorManager senSensorManager;
private Sensor senAccelerometer, senLightsensor, senTemperatureSensor;
private boolean isRunning;
private Handler myHandler = new Handler();
private float ACx, ACy, ACz;
//UI variables
private RelativeLayout relativeLayout;
private TextView LightResult, Debug, AcceleroResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senLightsensor = senSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
senTemperatureSensor = senSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senLightsensor , SensorManager.SENSOR_DELAY_NORMAL);
LightResult = (TextView) findViewById(R.id.LightFound);
AcceleroResult = (TextView) findViewById(R.id.AcceleroResult);
Debug = (TextView) findViewById(R.id.Debug);
}
/**
* using isRunning for each sensors ensures no unneeded updates are happening when app is turned off.
*/
@Override
public void onSensorChanged(SensorEvent event) {
Sensor mySensor = event.sensor;
myHandler.post( new Runnable() {
public void run() {
LightResult.setText(String.valueOf(lx));
AcceleroResult.setText(String.valueOf(ACx));
}
}
);
if (mySensor.getType() == Sensor.TYPE_LIGHT && isRunning) {
float lx = event.values[0];
LightResult.setText(String.valueOf(lx));
}
else if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER && isRunning) {
ACx = event.values[0];
ACy = event.values[1];
ACz = event.values[2];
AcceleroResult.setText(String.valueOf(ACx));
}
else if(mySensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE && isRunning){
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
//Sensors dont run when app is not in foreground
protected void onPause() {
super.onPause();
senSensorManager.unregisterListener(this);
isRunning = false;
}
//Turns sensors on when the app is in the foreground
protected void onResume() {
super.onResume();
senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senTemperatureSensor, SensorManager.SENSOR_DELAY_NORMAL);
senSensorManager.registerListener(this, senLightsensor, SensorManager.SENSOR_DELAY_NORMAL);
isRunning = true;
}
}