views:

985

answers:

2

I am writing a program and I am able to get the light sensor value and current battery level, but only the light value changes and when the battery level changes. Is there a way to get these two values anytime? Like when a user runs my program, I would like to grab the current values right away instead of having to wait for them to change.

+1  A: 

If you have the code to receive the value when it changes, you could store the value in a variable and when on every change just update the variable with a setter method. Then, whenever you need the current value anytime, just call the variable using a getter method.

So if your method looks like this

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;
}

You can have a getter method to return the currentl battery level, rawlevel, and you can do the same for the light sensor value.

Anthony Forloney
that wouldn't work for me and after researching it some i found this out about it: There is no android.os.SystemProperties in the current SDK. That is a class in the source code for use by the firmware only.Is there any other way to get the light sensor value and the battery level without waiting for it to change?
John
I updated my answer, it's an alternative approach if there is no *direct* way to return the value at a given time.
Anthony Forloney
A: 

I need to display Battery Level Stats in my Android app. All i know that there is one api i.e. android.os.BatteryManager that we can use.

Wonder how can i obtain Battery Stats?

Maxood