android - get light level every ten 10 minutes
My app needs to have an updated light level value (a 10-15 minute delay is fine or something) (this is not a commercial app) within its background service....
I know how to retrieve the light value using a SensorEventListener and the SensorManager but in the API docs it says explicitly that if you don't unregister the listener when you don't need it it will drain your battery in just a few hours.
now my question is....how can I use the listener along with the sensor manager to retrieve a light level value every 10-15 minutes?
Could I use something like the below with a Timer that runs this task every 10-15 minutes?
private Timer开发者_JS百科Task lightSensorTimer = new TimerTask() {
@Override
public void run() {
if (sensorManager != null) {
Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor != null) {
sensorManager.registerListener(sensorListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
while (newLightLevel == lightLevel) {
try {
**Thread.sleep(1000);**
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted exception in lightsensor timer: " + e.getMessage());
}
}
PhoneEvents.this.lightLevel = PhoneEvents.this.newLightLevel;
sensorManager.unregisterListener(sensorListener, lightSensor);
}
}
}
};
The sensoreventlistener does nothing but this:
private SensorEventListener sensorListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
PhoneEvents.this.newLightLevel = event.values[0];
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
};
I'm not even sure if you can use Thread.sleep within a timer task. But I have ready that TimerTasks need to finish quickly otherwise they batch up.
Is there a cleaner solution for something like this?
Thanks
Regards, Andreas
You should use an alarm that calls a serviceIntent.
Start the alarm every 15 minutes:
AlarmManager mgr=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(this, YourService.class);
PendingIntent pi=PendingIntent.getService(this, 0, i, 0);
mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
and your service looks like this:
public class YourServiceextends IntentService {
public YourService() {
super("YourService");
}
@Override
protected void onHandleIntent(Intent intent) {
//do something
}
}
精彩评论