验证中...
Languages: Java
Categories: Android 组件
Latest update 2019-06-25 17:55
MainActivity.java
Raw Copy
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView mtextView1;
private TextView mtextView2;
private TextView mtextView3;
private SensorManager sm;
private static final String TAG = "sensor";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iniView();
}
@Override
protected void onResume() {
super.onResume();
setSensor();
SensorManager mSensorManager;
List<Sensor> sensorList;
// 实例化传感器管理者
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// 得到设置支持的所有传感器的List
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
List<String> sensorNameList = new ArrayList<String>();
for (Sensor sensor : sensorList) {
Log.d(TAG, "onResume: "+sensor.getName());
}
}
public void iniView() {
mtextView1 = (TextView) findViewById(R.id.textView1);
mtextView2 = (TextView) findViewById(R.id.textView2);
mtextView3 = (TextView) findViewById(R.id.textView3);
}
public void setSensor() {
//创建一个SensorManager来获取系统的传感器服务
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
/*
* 最常用的一个方法 注册事件
* 参数1 :SensorEventListener监听器
* 参数2 :Sensor 一个服务可能有多个Sensor实现,此处调用getDefaultSensor获取默认的Sensor
* 参数3 :模式 可选数据变化的刷新频率,多少微秒取一次。
* */
// 为磁场传感器注册监听器
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if(sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
float X_lateral = sensorEvent.values[0];
float Y_longitudinal = sensorEvent.values[1];
float Z_vertical = sensorEvent.values[2];
mtextView1.setText("x轴的磁场强度\n"+ X_lateral );
mtextView2.setText("y轴的磁场强度\n"+ Y_longitudinal );
mtextView3.setText("z轴的磁场强度\n"+ Z_vertical );
}
//复写onAccuracyChanged方法
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "onAccuracyChanged");
}
@Override
public void onPause() {
sm.unregisterListener(this);
super.onPause();
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025