package com.example.day14_sensor; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.util.ArrayList; import java.util.List; 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); List<Sensor> sensorList = sensor.getSensorList(Sensor.TYPE_ALL); ArrayList<String> list = new ArrayList<>(); for (Sensor s:sensorList){ String str=" "+"设备名称:"+s.getName()+" 设备的版本:"+s.getVersion()+" 供应商:"+s.getVendor(); list.add(str); } text.setText("经检测手机有"+list.size()+"个传感器,分别是: "+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(" y方向的加速度"+values[1]); // builder.append(" z方向的加速度:"+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(" y方向的度量:"+values1[1]); builder1.append(" z方向的度量:"+values1[2]); text.setText(builder1.toString()); break; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }