The sensor in Android --- light sensor

When it comes to the light sensor, some people feel that they don’t use it much, but the automatic brightness adjustment of the mobile phone itself is the light sensor used, that is, the light sensor in the mobile phone. Is this function turned on in your mobile phone?

little introduction

So what the hell is a light sensor? It is used to detect the intensity of light around the mobile phone, the unit is lux, it is usually placed on the head of the mobile phone, near the front camera, you can look at your mobile phone, hold your finger to see if the brightness of the mobile phone will dim, the light The sensor and other sensor development steps are the same (it seems to be such a process)

development process

1. Get the sensor manager object

// 获取传感器管理者对象
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

2. Obtain the specified sensor object, here is the light sensor

// 获取光线传感器对象
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

3. Add a listener, preferably in onResume()

sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL);

4. Get the value of the current light intensity

float light = event.values[0];

5. Don't forget to unregister when not in use, no longer receive sensor updates

sensorManager.unregisterListener(this,sensor);

full code

public class LightActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager sensorManager;
    private Sensor sensor;
    private TextView mTvLight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light);
        mTvLight=findViewById(R.id.tv_light);
        // 获取传感器管理者对象
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // 获取光线传感器对象
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    }
    @Override
    protected void onResume() {
        super.onResume();
        //添加监听器
        sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sensorManager != null) {
            //解除注册,不再接收任何传感器的更新。
            sensorManager.unregisterListener(this,sensor);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float light = event.values[0];
        StringBuffer buffer = new StringBuffer();
        buffer.append("现在的光照强度:").append(light).append("lux");
        mTvLight.setText(buffer);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

For more mobile phone sensor usage, please see Sensors in Android (total)

Guess you like

Origin blog.csdn.net/lanrenxiaowen/article/details/108122011