package com.yifei.myapplication;
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.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
SensorManager manager;
Sensor sensor;
private MySensorEventListener mySensorEventListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
//得到传感器管理器实例
manager = (SensorManager) getSystemService(SENSOR_SERVICE);
mySensorEventListener = new MySensorEventListener();
if (manager != null) {
//获取光照传感器实例
sensor = manager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (sensor != null) {
//注册光照传感器监听器
manager.registerListener(mySensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
}
//监听器
private class MySensorEventListener implements SensorEventListener {
//当传感器的精度发送变化时通用的方法
@Override
public void onSensorChanged(SensorEvent event) {
//光照传感器监听数值
float value = event.values[0];//当values[]数组下标为0时,就是当前的光照强度
Log.d("MainActivity12", "onSensorChanged: "+value);
}
//当传感器的精度发生变化式调用该方法
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
//activity销毁时,销毁传感器的监听器
@Override
protected void onDestroy() {
super.onDestroy();
manager.unregisterListener(mySensorEventListener);
}
}