传感器的简单实现

public class MainActivity extends AppCompatActivity implements SensorEventListener{

  private TextView text;

  @Override protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

      initView();

      //获取传感器的管理

       SensorManager sensor = (SensorManager) getSystemService(SENSOR_SERVICE);

       ListsensorList = sensor.getSensorList(Sensor.TYPE_ALL);

      ArrayListlist = new ArrayList<>();

for (Sensor s:sensorList){

String str="\n"+"设备名称:"+s.getName()+"\n设备的版本:"+s.getVersion()+"\n供应商:"+s.getVendor();

list.add(str);

}

text.setText("经检测手机有"+list.size()+"个传感器,分别是:\n"+list.toString());

Sensor msensor1 = sensor.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);

sensor.registerListener(this,msensor1,SensorManager.SENSOR_DELAY_GAME);

Sensor msensor = sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

//监听事件

sensor.registerListener(this,msensor,SensorManager.SENSOR_DELAY_GAME);

Sensor light = sensor.getDefaultSensor(Sensor.TYPE_LIGHT);

sensor.registerListener(this,light,SensorManager.SENSOR_DELAY_GAME);

}

private void initView() {

text = (TextView) findViewById(R.id.text);

}

@Override

public void onSensorChanged(SensorEvent event) {

int type = event.sensor.getType();

switch (type){

case Sensor.TYPE_LIGHT:

float[] values = event.values;

StringBuilder builder = new StringBuilder();

builder.append("光感度:"+values[0]);

//                builder.append("\ny方向的加速度"+values[1]);

//                builder.append("\nz方向的加速度:"+values[2]);

text.setText(builder.toString());

break;

case Sensor.TYPE_GAME_ROTATION_VECTOR:

float[] values1 = event.values;

StringBuilder builder1 = new StringBuilder();

builder1.append("x方向的度量:"+values1[0]);

builder1.append("\ny方向的度量:"+values1[1]);

builder1.append("\nz方向的度量:"+values1[2]);

text.setText(builder1.toString());

break;

}

}

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

}

你可能感兴趣的:(传感器的简单实现)