如何获取传感器值作为变量

本文关键字:变量 传感器 何获取 获取 | 更新日期: 2023-09-27 18:33:35

这可能是一个愚蠢的问题,但我自己无法处理。我设法获得了光传感器的价值。我需要将此值作为变量获取,但我无法访问变量 X。 你能帮我吗?

public class lightWakeup extends AppCompatActivity {
    ImageButton imageButton;
    Intent navrat;
    MediaPlayer mp;
    TextView text;
    SensorManager sensorManager;
    Sensor sensor;
    float x;
    public float c;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light_wakeup);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        text = (TextView)findViewById(R.id.textView);
                //zapnuti hudby
        mp = MediaPlayer.create(this, R.raw.hypnothis);
        mp.setVolume(50, 50);
        mp.start();
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        text.setText(String.valueOf(c));


        imageButton = (ImageButton) findViewById(R.id.imageButton);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
                navrat = new Intent(getApplicationContext(), MainPage.class);
                startActivity(navrat);
            }
        });
    }
    public void onResume() {
        super.onResume();
        sensorManager.registerListener(lightListener, sensor,
                SensorManager.SENSOR_DELAY_NORMAL);
    }
    public void onStop() {
        super.onStop();
        sensorManager.unregisterListener(lightListener);
    }
    public SensorEventListener lightListener = new SensorEventListener() {
        public void onAccuracyChanged(Sensor sensor, int acc) { }
        public void onSensorChanged(SensorEvent event) {
            x = event.values[0];
            text.setText((int)x);
        }
    };
}

如何获取传感器值作为变量

您需要将变量 x 设置为公共修饰符:

public float x;

默认情况下,不带修饰符的类变量在 C# 中设置为"内部"。您可以在 https://msdn.microsoft.com/en-us/library/ms173121.aspx 查看有关变量修饰符的信息