fix: 降低耗电 - 时钟改每分钟更新+息屏暂停,健康检查改15分钟+不唤醒
1. 时钟从每秒更新改为每分钟,用 repeatOnLifecycle 息屏自动暂停 2. MQTT 健康检查从5分钟改为15分钟,用 ELAPSED_REALTIME 不强制唤醒设备 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,6 @@ import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import com.xiaoqu.watch.service.manager.MqttManager
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
@@ -15,16 +14,16 @@ import javax.inject.Inject
|
||||
/**
|
||||
* MQTT 连接健康检查广播接收器
|
||||
*
|
||||
* 通过 AlarmManager.setExactAndAllowWhileIdle() 定期触发,
|
||||
* 在 Doze 模式的维护窗口中检查 MQTT 连接状态,断连则重连。
|
||||
* 通过 AlarmManager 定期触发(不强制唤醒,等系统维护窗口),
|
||||
* 检查 MQTT 连接状态,断连则重连。
|
||||
* 同时确保 MqttService 前台服务存活。
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class MqttAlarmReceiver : BroadcastReceiver() {
|
||||
|
||||
companion object {
|
||||
/** 检查间隔:5 分钟(Doze 维护窗口至少 10 分钟,5 分钟能抓到窗口期) */
|
||||
private const val CHECK_INTERVAL_MS = 5 * 60 * 1000L
|
||||
/** 检查间隔:15 分钟(减少唤醒频率,前台服务+电池白名单已足够保活) */
|
||||
private const val CHECK_INTERVAL_MS = 15 * 60 * 1000L
|
||||
|
||||
/** 启动定时健康检查 */
|
||||
fun schedule(context: Context) {
|
||||
@@ -35,20 +34,12 @@ class MqttAlarmReceiver : BroadcastReceiver() {
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
// setExactAndAllowWhileIdle: Doze 模式下也能触发
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
alarmManager.setExactAndAllowWhileIdle(
|
||||
AlarmManager.ELAPSED_REALTIME_WAKEUP,
|
||||
SystemClock.elapsedRealtime() + CHECK_INTERVAL_MS,
|
||||
pendingIntent
|
||||
)
|
||||
} else {
|
||||
alarmManager.setExact(
|
||||
AlarmManager.ELAPSED_REALTIME_WAKEUP,
|
||||
SystemClock.elapsedRealtime() + CHECK_INTERVAL_MS,
|
||||
pendingIntent
|
||||
)
|
||||
}
|
||||
// 不唤醒设备,等系统下次维护窗口时执行(省电)
|
||||
alarmManager.set(
|
||||
AlarmManager.ELAPSED_REALTIME, // 不强制唤醒
|
||||
SystemClock.elapsedRealtime() + CHECK_INTERVAL_MS,
|
||||
pendingIntent
|
||||
)
|
||||
Timber.d("MqttAlarm: 已设置 ${CHECK_INTERVAL_MS / 1000}s 后检查")
|
||||
}
|
||||
|
||||
|
||||
@@ -378,12 +378,14 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 每秒更新时钟 */
|
||||
/** 每分钟更新时钟(息屏时自动暂停,省电) */
|
||||
private fun startClockUpdater() {
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
while (isActive) {
|
||||
updateClock()
|
||||
delay(1000)
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
while (isActive) {
|
||||
updateClock()
|
||||
delay(60_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user