The sensor in Android --- temperature sensor

Some people think that this temperature sensor is useless. Indeed, in the actual development process, there is rarely such a need, so that some mobile phones directly cancel the function of this sensor. Do you also think that the temperature and even humidity sensors are useless? These information can be obtained from the Internet. These small functions may be used in weather forecasting projects. Record them here and paste the code directly, because my mobile phone does not support temperature sensors and I have not measured them specifically, but I believe this. There is no problem with the piece of code, after all, the reference is closed, ha

 

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_AMBIENT_TEMPERATURE);
    }
    @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) {
        if(event.sensor.getType()==Sensor.TYPE_AMBIENT_TEMPERATURE){
            float temperature=event.values[0];
            mTvLight.setText(String.valueOf(temperature)+"°C");
        }else {
            ToastUtils.showShort("不支持");
        }
    }

    @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/108123299