2

我正在编写一个程序,我能够获取光传感器值和当前电池电量,但只有光值变化以及电池电量何时变化。有没有办法随时获得这两个值?就像用户运行我的程序一样,我想立即获取当前值,而不必等待它们更改。

4

2 回答 2

2

如果您有代码在更改时接收值,则可以将值存储在变量中,并且在每次更改时只需使用 setter 方法更新变量。然后,只要您随时需要当前值,只需使用 getter 方法调用变量即可。

所以如果你的方法看起来像这样

private void monitorBatteryState() {
    BroadcastReceiver battReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {

            context.unregisterReceiver(this);
            int rawlevel = intent.getIntExtra("level", -1);
            int scale = intent.getIntExtra("scale", -1);
            int status = intent.getIntExtra("status", -1);
            int health = intent.getIntExtra("health", -1);
            int level = -1;  // percentage, or -1 for unknown
            if (rawlevel >= 0 && scale > 0) {
                level = (rawlevel * 100) / scale;
            }
            setBatteryLevel(rawlevel);  // setter method.
            } 
    }

public void setBatteryLevel(rawlevel) {
  batteryLevel = rawlevel;
}

public int getBatteryLevel() {
  return rawlevel;
}

您可以有一个 getter 方法来返回当前的电池电量,rawlevel您可以对光传感器值执行相同的操作。

于 2010-02-15T03:31:26.827 回答
0

put this in your mainActivity: this is for the light sensor value only because I see someone else has posted about the battery level.

SensorManager mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
//don't know if you can put lightSensorValue here, if not try adding it as a member field
final int lightSensorValue;

mSensorManager.registerListener(new SensorEventListener()
{
    public void onAccuracyChanged(Sensor sensor, int accuracy) 
    {
        //do something when accuracy is changed, you probably don't need this
    }

    public void onSensorChanged(SensorEvent event)
    {
        lightSensorValue = event.values[0];
    }

}, mLight, SensorManager.SENSOR_DELAY_NORMAL);

EDIT: i read your question again and see that you want to get it manually anytime. Well this value gets updated whenever the value is changed, so you are always getting the most recent information.

You can try setting changing the delay to SensorManager.SENSOR_DELAY_FASTEST and the refresh rate will be a lot faster.

于 2013-10-15T21:39:56.117 回答