我发现它不可靠,使用ACTION_TIME_CHANGED
and ACTION_TIMEZONE_CHANGED
. 有时它会被触发,有时即使我手动更改设备时间也不会触发。当手动更改设备时间时ACTION_TIME_CHANGED
,我的设备上会调用两次。
根据您的用例和需求,您可以System.currentTimeMillis()
通过每 X 秒检查一次来计算设备时间(仅限)是否已手动更改。但它不会检测时区是否已更改。由于System.currentTimeMillis()
可能会更改,但SystemClock.elapsedRealtime()
除非设备启动,否则不会更改,因此您可以检测是否System.currentTimeMillis()
更改。
在 Kotlin 中,示例实现如下所示:
private val TIME_CHANGE_CONTROL_INTERVAL = 10_000L
private val TIME_CHANGE_THRESHOLD = 1_000L
private var lastUptimeTime = SystemClock.elapsedRealtime()
private var lastEpochTime = System.currentTimeMillis()
private lateinit var timeChangeJob: Job
private fun detectTimeChange() {
val uptimeDifference = SystemClock.elapsedRealtime() - lastUptimeTime
val epochDifference = System.currentTimeMillis() - lastEpochTime
val timeChange = Math.abs(uptimeDifference - epochDifference)
if (timeChange > TIME_CHANGE_THRESHOLD) {
// Time has changed more than 1sec
}
lastUptimeTime = SystemClock.elapsedRealtime()
lastEpochTime = System.currentTimeMillis()
}
fun listenToDeviceTimeChanges() {
if (::timeChangeJob.isInitialized) timeChangeJob.cancel()
timeChangeJob = Job()
GlobalScope.launch(timeChangeJob) {
while (isActive) {
detectTimeChange()
delay(TIME_CHANGE_CONTROL_INTERVAL)
}
}
}
fun unlistenToDeviceTimeChanges() {
if (::timeChangeJob.isInitialized) timeChangeJob.cancel()
lastUptimeTime = SystemClock.elapsedRealtime()
lastEpochTime = System.currentTimeMillis()
}