0
我的應用需要在其後臺服務中有一個更新的光照水平值(10-15分鐘的延遲是好的或者其他)(這不是商業應用)....android - 每10分鐘獲取一次光照水平10分鐘
我知道如何使用SensorEventListener和SensorManager檢索燈值,但在API文檔中它明確指出,如果您在不需要時取消註冊偵聽器,它將耗盡您的電池幾個小時。
現在我的問題是....我怎樣才能使用監聽器與傳感器管理器每10-15分鐘檢索一個亮度值?
我可以使用類似下面的東西,每10-15分鐘運行一次這個任務的計時器?
private TimerTask 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);
}
}
}
};
的sensoreventlistener什麼也不做,但這樣的:
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) {
}
};
我甚至不知道你是否能針對計時器任務中使用的Thread.sleep。但是我已經準備好了,TimerTasks需要快速完成,否則它們會批量增加。
有沒有比這個更清潔的解決方案?
感謝
問候, 安德烈亞斯
我已經有一個服務的前臺服務。所以我不需要每15分鐘喚醒一次設備。所以你說要在我的前臺服務中使用警報管理器? – kkudi 2011-03-18 20:41:10
不可以。不要使用前臺服務,只能通過警報啓動服務。 – Falmarri 2011-03-18 20:43:48
嗯,我不知道你的服務是什麼。我認爲你應該爲意圖使用警報,並保持整潔,爲什麼不爲這項任務提供單獨的服務。如果別的東西也在運行,我想也沒關係。所以我認爲上面的代碼還是不錯的。只需在onHandleIntent中處理你的東西。 (嗯,@falmarri更快:D ..但那;)) – Nanne 2011-03-18 20:44:32