監控電池電量和充電狀態
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
如要調整背景更新頻率,以減少這些更新對電池續航力的影響,建議您先檢查目前的電池電量和充電狀態。
執行應用程式更新對電池續航力的影響取決於裝置的電池電量和充電狀態。裝置透過 AC 充電時執行更新的影響
無法找出原因,因此在多數情況下,你可以在裝置連上網路時,盡可能提高刷新率
加入牆上充電器相反地,如果裝置正在放電,降低更新率有助於延長電池續航力。
同樣地,您也可以檢查電池電量,在電池電量幾乎耗盡時減少更新頻率,甚至停止更新。
判斷目前的充電狀態
首先,確定目前的收費狀態。BatteryManager
會在含有充電狀態的固定 Intent
中廣播所有電池和充電詳細資料。
由於這是固定式意圖,因此您不必註冊 BroadcastReceiver
,只要呼叫 registerReceiver
傳入,即可
null
做為接收器,如下一個程式碼片段所示,目前的電池狀態意圖為
。您可以在這裡傳入實際的 BroadcastReceiver
物件,但
我們會在後續章節處理更新,因此並非必要。
Kotlin
val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
context.registerReceiver(null, ifilter)
}
Java
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
你可以擷取目前的充電狀態,以及裝置是否正在充電
目前是透過 USB 或 AC 充電器充電:
Kotlin
val status: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING
|| status == BatteryManager.BATTERY_STATUS_FULL
// How are we charging?
val chargePlug: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
val usbCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
val acCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
Java
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
一般來說,在裝置
連接 AC 充電器,若為 USB 充電,請降低速率,然後降低到 AC 充電器。
電池在放電時可再重設
監控充電狀態的變化
充電狀態會隨著裝置插入充電器而變更,因此請務必監控充電狀態,並據此調整刷新率。
BatteryManager
會在裝置連上或斷開電源時廣播動作。在使用者無法在應用程式中
執行期間,特別是這些事件應該會影響您啟動應用程式的頻率,
會啟動背景更新,因此您必須在資訊清單中註冊 BroadcastReceiver
,以監聽兩個事件,方法是定義
意圖篩選器中的 ACTION_POWER_CONNECTED
和 ACTION_POWER_DISCONNECTED
。
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
判斷目前的電池電量
在某些情況下,判斷目前的電池電量也有幫助。如果電池電量低於特定等級,您可以選擇降低背景更新率。
您可以從電池狀態意圖中擷取目前的電池電量和刻度,如以下所示:
Kotlin
val batteryPct: Float? = batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
level * 100 / scale.toFloat()
}
Java
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float)scale;
回應電池電量大幅變化
您無法輕易持續監控電池狀態,但這並非必要。
一般來說,監控電池電量的影響,比應用程式的正常行為對電池的影響更大。舉例來說,註冊
資訊清單中的 BroadcastReceiver
,在電量過低時取消待處理的工作
主要運作會更耗電
根本不可能
Android 8.0)。而是可以針對工作設下限制,描述其執行時機。
讓系統做出決定,而不必啟動應用程式。
一般來說,在電池電量嚴重不足時,不執行背景更新是較好的做法。無論資料有多新,如果手機在您使用前自行關機,您都無法使用這些資料。如要這麼做,請使用 WorkManager 程式庫,並搭配BatteryNotLow
限制條件,指定在電池電量不足時 (除了任何相關 NetworkType
限制條件外),工作不應執行。
在許多情況下,為裝置充電的行為與裝設裝置並不相關
以便在座架上詳情請參閱「判斷及監控裝置是否插入座架和座架類型」。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Monitor the Battery Level and Charging State\n\nWhen you're altering the frequency of your background updates to reduce the effect of those\nupdates on battery life, checking the current battery level and charging state is a good place to\nstart.\n\nThe battery-life impact of performing application updates depends on the battery level and\ncharging state of the device. The impact of performing updates while the device is charging over AC\nis negligible, so in most cases you can maximize your refresh rate whenever the device is connected\nto a wall charger. Conversely, if the device is discharging, reducing your update rate helps\nprolong the battery life.\n\nSimilarly, you can check the battery charge level, potentially reducing the frequency of---or\neven stopping---your updates when the battery charge is nearly exhausted.\n\nDetermine the current charging state\n------------------------------------\n\nStart by determining the current charge status. The [BatteryManager](/reference/android/os/BatteryManager)\nbroadcasts all battery and charging details in a sticky [Intent](/reference/android/content/Intent) that includes\nthe charging status.\n\nBecause it's a sticky intent, you don't need to register a [BroadcastReceiver](/reference/android/content/BroadcastReceiver)---by simply calling `registerReceiver` passing in\n`null` as the receiver as shown in the next snippet, the current battery status intent is\nreturned. You could pass in an actual [BroadcastReceiver](/reference/android/content/BroadcastReceiver) object here, but\nwe'll be handling updates in a later section so it's not necessary. \n\n### Kotlin\n\n```kotlin\nval batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter -\u003e\n context.registerReceiver(null, ifilter)\n}\n```\n\n### Java\n\n```java\nIntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);\nIntent batteryStatus = context.registerReceiver(null, ifilter);\n```\n\nYou can extract both the current charging status and, if the device is being charged, whether\nit's charging via USB or AC charger:\n\n\n### Kotlin\n\n```kotlin\nval status: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1\nval isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING\n || status == BatteryManager.BATTERY_STATUS_FULL\n\n// How are we charging?\nval chargePlug: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1\nval usbCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_USB\nval acCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_AC\n```\n\n### Java\n\n```java\n// Are we charging / charged?\nint status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);\nboolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||\n status == BatteryManager.BATTERY_STATUS_FULL;\n\n// How are we charging?\nint chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);\nboolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;\nboolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;\n```\n\nTypically you should maximize the rate of your background updates in the case where the device is\nconnected to an AC charger, reduce the rate if the charge is over USB, and lower it\nfurther if the battery is discharging.\n\nMonitor changes in charging state\n---------------------------------\n\nThe charging status can change as easily as a device can be plugged in, so it's important to\nmonitor the charging state for changes and alter your refresh rate accordingly.\n\nThe [BatteryManager](/reference/android/os/BatteryManager) broadcasts an action whenever the device is connected or\ndisconnected from power. It's important to receive these events even while your app isn't\nrunning---particularly as these events should impact how often you start your app in order to\ninitiate a background update---so you should register a [BroadcastReceiver](/reference/android/content/BroadcastReceiver) in your manifest to listen for both events by defining the\n[ACTION_POWER_CONNECTED](/reference/android/content/Intent#ACTION_POWER_CONNECTED) and [ACTION_POWER_DISCONNECTED](/reference/android/content/Intent#ACTION_POWER_DISCONNECTED) within an intent filter. \n\n```xml\n\u003creceiver android:name=\".PowerConnectionReceiver\"\u003e\n \u003cintent-filter\u003e\n \u003caction android:name=\"android.intent.action.ACTION_POWER_CONNECTED\"/\u003e\n \u003caction android:name=\"android.intent.action.ACTION_POWER_DISCONNECTED\"/\u003e\n \u003c/intent-filter\u003e\n\u003c/receiver\u003e\n```\n\nDetermine the current battery level\n-----------------------------------\n\nIn some cases it's also useful to determine the current battery level. You may choose to reduce\nthe rate of your background updates if the battery charge is below a certain level.\n\nYou can find the current battery charge by extracting the current battery level and scale from\nthe battery status intent as shown here: \n\n### Kotlin\n\n```kotlin\nval batteryPct: Float? = batteryStatus?.let { intent -\u003e\n val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)\n val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)\n level * 100 / scale.toFloat()\n}\n```\n\n### Java\n\n```java\nint level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);\nint scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);\n\nfloat batteryPct = level * 100 / (float)scale;\n```\n\nReact to significant changes in battery level\n---------------------------------------------\n\nYou can't easily continually monitor the battery state, but you don't need to.\n\nGenerally speaking, the impact of monitoring the battery level has a greater\nimpact on the battery than your app's normal behavior. For example, registering a\n`BroadcastReceiver` in the manifest to cancel pending work when the battery is low will\nmainly serve to drain the battery further (and is therefore\n[impossible since\nAndroid 8.0](/develop/background-work/background-tasks/broadcasts/broadcast-exceptions)). Instead, you can provide constraints on work that describe when it should be run,\nallowing the system to make the decision without spending power starting your app.\n\nIt is generally good practice to not run your background updates when the battery is\ncritically low. It doesn't matter how fresh your data is if the phone turns itself off before you\ncan make use of it. To do this,\n[use the WorkManager library](/develop/background-work/background-tasks/persistent/getting-started)\nwith a\n[`BatteryNotLow` constraint](/develop/background-work/background-tasks/persistent/getting-started/define-work#work-constraints)\nto specify that the work should not be run if the battery is low (in addition to any relevant\n`NetworkType` constraints).\n\nIn many cases, the act of charging a device is coincident with putting it\ninto a dock. To learn more, see\n[Determine and\nmonitor the docking state and type](/training/monitoring-device-state/docking-monitoring)."]]