Commit 8dcfd5a8 authored by Mygod's avatar Mygod

Reduce battery usage - prevent unnecessary notification updates

parent ef162cd4
...@@ -86,8 +86,7 @@ trait BaseService extends Service { ...@@ -86,8 +86,7 @@ trait BaseService extends Service {
if (callbackCount == 0 && timer == null) { if (callbackCount == 0 && timer == null) {
val task = new TimerTask { val task = new TimerTask {
def run { def run {
TrafficMonitor.updateRate() if (TrafficMonitor.updateRate()) updateTrafficRate()
updateTrafficRate()
} }
} }
timer = new Timer(true) timer = new Timer(true)
...@@ -95,6 +94,9 @@ trait BaseService extends Service { ...@@ -95,6 +94,9 @@ trait BaseService extends Service {
} }
callbacks.register(cb) callbacks.register(cb)
callbackCount += 1 callbackCount += 1
TrafficMonitor.updateRate()
cb.trafficUpdated(TrafficMonitor.getTxRate, TrafficMonitor.getRxRate,
TrafficMonitor.getTxTotal, TrafficMonitor.getRxTotal)
} }
} }
......
...@@ -18,6 +18,7 @@ object TrafficMonitor { ...@@ -18,6 +18,7 @@ object TrafficMonitor {
var txLast: Long = _ var txLast: Long = _
var rxLast: Long = _ var rxLast: Long = _
var timestampLast: Long = _ var timestampLast: Long = _
@volatile var dirty = true
private val units = Array("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB", "NB", "DB", "CB") private val units = Array("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB", "NB", "DB", "CB")
private val numberFormat = new DecimalFormat("@@@") private val numberFormat = new DecimalFormat("@@@")
...@@ -32,21 +33,42 @@ object TrafficMonitor { ...@@ -32,21 +33,42 @@ object TrafficMonitor {
else numberFormat.format(n) + ' ' + units(i) else numberFormat.format(n) + ' ' + units(i)
} }
def updateRate() { def updateRate() = {
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val delta = now - timestampLast val delta = now - timestampLast
var updated = false
if (delta != 0) { if (delta != 0) {
txRate = (txTotal - txLast) * 1000 / delta if (dirty) {
rxRate = (rxTotal - rxLast) * 1000 / delta txRate = (txTotal - txLast) * 1000 / delta
txLast = txTotal rxRate = (rxTotal - rxLast) * 1000 / delta
rxLast = rxTotal txLast = txTotal
rxLast = rxTotal
dirty = false
updated = true
} else {
if (txRate != 0) {
txRate = 0
updated = true
}
if (rxRate != 0) {
rxRate = 0
updated = true
}
}
timestampLast = now timestampLast = now
} }
updated
} }
def update(tx: Long, rx: Long) { def update(tx: Long, rx: Long) {
txTotal = tx if (txTotal != tx) {
rxTotal = rx txTotal = tx
dirty = true
}
if (rxTotal != rx) {
rxTotal = rx
dirty = true
}
} }
def reset() { def reset() {
...@@ -56,6 +78,7 @@ object TrafficMonitor { ...@@ -56,6 +78,7 @@ object TrafficMonitor {
rxTotal = 0 rxTotal = 0
txLast = 0 txLast = 0
rxLast = 0 rxLast = 0
dirty = true
} }
def getTxTotal(): String = { def getTxTotal(): String = {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment