How to get light sensor value and battery level anytime for android?
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 wo开发者_Python百科uld like to grab the current values right away instead of having to wait for them to change.
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.
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.
精彩评论