用户最怕 App 耗电。后台偷偷跑、GPS 一直定位、网络频繁唤醒,都是电量杀手。电量优化的本质,是减少不必要的系统唤醒。
一、Doze 和 App Standby
Android 6.0 引入的 Doze 模式:
屏幕关闭且设备静止一段时间后进入 Doze
期间网络、闹钟、Job 被推迟到窗口期集中执行
设备移动或插充电线会退出 Doze
App Standby:
用户不常用 App 会被系统标记为 idle
idle 期间后台活动受限
不要试图绕过这些限制,要顺应它们设计后台任务。
二、后台任务选型
不要再用普通 Service 做常驻后台。
三、定位优化
val request = LocationRequest.Builder(
Priority.PRIORITY_BALANCED_POWER_ACCURACY,
60_000L
).build()
前台用高精度,后台用低精度
不需要实时定位时用被动定位
用完记得
removeLocationUpdates用 Geofencing 替代轮询定位
四、网络与唤醒锁
批量网络请求,减少电台唤醒
用 JobScheduler/WorkManager 让系统批量处理
WakeLock 用完立即释放
不要用
PARTIAL_WAKE_LOCK长期持有
五、电量监控
Android Studio Profiler 看电量消耗
Battery Historian 分析耗电曲线
关注
AlarmManager、JobScheduler、Location的唤醒次数线上用 APM 收集用户耗电数据
小结
顺应 Doze/Standby 设计后台任务
后台用 WorkManager,前台用 Foreground Service
定位按场景选择精度,用完即释放
批量网络请求,避免频繁唤醒电台
下一篇,我们聊安全进阶:证书固定、Root 检测与数据加密。
参考阅读
引用链接
[1]Android 电量优化: https://developer.android.com/topic/performance/power
[2]Doze and App Standby: https://developer.android.com/training/monitoring-device-state/doze-standby