作者:二狗子 | 来源:互联网 | 2023-10-10 17:00
packagebw.com.bw_day09_sensor.demo02;importandroid.content.Context;importandroid.hardware
package bw.com.bw_day09_sensor.demo02;
import android.content.Context;
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.EditText;
import bw.com.bw_day09_sensor.R;
public class SensorActivity02 extends AppCompatActivity implements SensorEventListener{
private EditText et_01;
private EditText et_02;
private SensorManager sensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor02);
initView();
//1, 得到传感器的管理器对象
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
//2,设置监听器
@Override
protected void onStart() {
super.onStart();
sensorManager.registerListener(this,sensorManager.getDefaultSensor(1),200);//重力加速度传感器
sensorManager.registerListener(this,sensorManager.getDefaultSensor(5),200);//光传感器
}
//3, 取消监听
@Override
protected void onStop() {
super.onStop();
sensorManager.unregisterListener(this);
}
//4, 检测数据的变化
@Override
public void onSensorChanged(SensorEvent event) {
//获取X,Y,Z 的值
float[] data = event.values;
//获取当前传感器的类型
int type = event.sensor.getType();
switch (type)
{
case 1:
et_01.setText("加速度传感器 : X = " + data[0] +" \n y = "+ data[1] +" \n z = "+data[2]);
break;
case 5:
et_02.setText("光传感器 : X = " + data[0] +" \n y = "+ data[1] +" \n z = "+data[2]);
break;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
} private void initView() {
et_01 = (EditText) findViewById(R.id.et_01);
et_02 = (EditText) findViewById(R.id.et_02);
}
}