針對電池續航力進行位置資訊使用最佳化
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
請採取下列行動,改善應用程式對裝置電池續航力的影響,以便使用定位服務。
移除定位更新通知
不必要的電池耗電是造成電力用盡的常見原因。
當活動的 onStart()
或 onResume()
生命週期方法包含對 requestlocationUpdates()
的呼叫,但在 onPause()
或 onStop()
生命週期方法中,卻沒有對應的 removeLocationUpdates()
呼叫,就可能發生這種情形。
您可以使用生命週期感知元件,妥善管理應用程式中的活動生命週期。詳情請參閱「使用生命週期感知元件處理生命週期」一文。
設定逾時
為防止電池耗電,請設定一個位置更新通知應停止的合理逾時時間。逾時設定可確保更新不會無限期地持續進行,在要求更新後但未移除更新的情況下 (例如,因為程式碼發生錯誤),還能保護應用程式。
針對整合式位置預測提供工具要求,請呼叫 setDurationMillis()
(接收代表自系統上次呼叫這個方法後的毫秒時間參數) 來新增逾時設定。您也可以使用這個方法,以時間長度表示到期時間。
如要在地理圍欄定位要求中新增逾時設定,請呼叫 setExpirationDuration()
方法。
批次處理要求
對於所有非前景用途,請批次處理多個要求。使用 setIntervalMillis()
方法指定計算位置的間隔時間。接著,使用 setMaxUpdateDelayMillis()
方法設定位置「傳送」至應用程式的間隔時間。請將值傳遞至 setMaxUpdateDelayMillis()
方法,該值應數倍於傳遞至 setIntervalMillis()
方法的值。以下列定位要求為例:
Kotlin
val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10 * 60 * 1000)
.setMaxUpdateDelayMillis(60 * 60 * 1000)
.build()
Java
LocationRequest request = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10 * 60 * 1000)
.setMaxUpdateDelayMillis(60 * 60 * 1000)
.build();
在這種情況下,系統大約每 10 分鐘計算一次位置,並且大概每小時批量傳送 6 個左右位置資料點。儘管您仍然每隔 10 分鐘左右就會收到位置更新通知,但由於每小時才喚醒您的裝置,因此可節省電力。
使用被動位置更新通知
在背景用途中,建議您限制位置更新通知次數。雖然 Android 8.0 (API 級別 26) 限制會強制執行這種做法,但在舊版裝置上執行的應用程式應盡可能設法限制背景位置資訊。
很可能當您的應用程式在背景執行時,另一個應用程式可能正在前景頻頻要求位置更新通知。定位服務為您的應用程式提供這些更新。請考慮以下列位置資訊要求,適時使用位置資料:
Kotlin
val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 15 * 60 * 1000)
.setMinUpdateIntervalMillis(2 * 60 * 1000)
.build()
Java
LocationRequest request = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 15 * 60 * 1000)
.setMinUpdateIntervalMillis(2 * 60 * 1000)
.build();
在上一個範例中,系統大約每 15 分鐘計算一次應用程式的位置。如果其他應用程式要求位置資訊,應用程式會以最長 2 分鐘的間隔時間收到資料。
雖然以被動方式使用位置資訊而未導致電池耗電,但在接收位置資料的位置時,會觸發費用昂貴的 CPU 或 I/O 作業,請務必格外小心謹慎。為盡量減少電池消耗,setMinUpdateIntervalMillis()
中指定的間隔時間不得太小。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。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,["# Optimize location use for battery life\n\nTake the following actions to [improve your app's\nimpact on a device's battery life](/develop/sensors-and-location/location/battery) when using location services.\n\nRemove location updates\n-----------------------\n\nA common source of unnecessary battery drain is the failure to remove location\nupdates when they are no longer needed.\n\nThis can happen when an activity's [`onStart()`](/reference/android/app/Activity#onStart()) or [`onResume()`](/reference/android/app/Activity#onResume())\nlifecycle methods contain a call to [`requestlocationUpdates()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#requestLocationUpdates(com.google.android.gms.location.LocationRequest,%20android.app.PendingIntent)) without a\ncorresponding call to [`removeLocationUpdates()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#removeLocationUpdates(com.google.android.gms.location.LocationCallback)) in the [`onPause()`](/reference/android/app/Activity#onPause()) or\n[`onStop()`](/reference/android/app/Activity#onStop()) lifecycle methods.\n\nYou can use lifecycle-aware components to better manage the lifecycle of the\nactivities in your app. For more information, see [Handling Lifecycles with\nLifecycle-Aware Components](/topic/libraries/architecture/lifecycle).\n\nSet timeouts\n------------\n\nTo guard against battery drain, set a reasonable timeout when location updates\nshould stop. The timeout ensures that updates don't continue indefinitely, and\nit protects the app in scenarios where updates are requested but not removed\n(for example, because of a bug in the code).\n\nFor a fused location provider request, add a timeout by calling\n[`setDurationMillis()`](https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.Builder#setDurationMillis(long)), which receives a parameter that represents the\ntime in milliseconds since the method was last called. You can also use the\nmethod to express the expiration time in terms of duration.\n\nTo add a timeout to a geofence location request, call the\n[`setExpirationDuration()`](https://developers.google.com/android/reference/com/google/android/gms/location/Geofence.Builder.html#setExpirationDuration(long)) method.\n\nBatch requests\n--------------\n\nFor all non-foreground use cases, batch multiple requests together. Use the\n[`setIntervalMillis()`](https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.Builder#setIntervalMillis(long)) method to specify the interval at which you would like\nlocation to be computed. Then, use the [`setMaxUpdateDelayMillis()`](https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.Builder#setMaxUpdateDelayMillis(long)) method to set\nthe interval at which location is *delivered* to your app. Pass a value to the\n`setMaxUpdateDelayMillis()` method that is a multiple of the value passed to the\n`setIntervalMillis()` method. For example, consider the following location request: \n\n### Kotlin\n\n val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10 * 60 * 1000)\n .setMaxUpdateDelayMillis(60 * 60 * 1000)\n .build()\n\n### Java\n\n LocationRequest request = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10 * 60 * 1000)\n .setMaxUpdateDelayMillis(60 * 60 * 1000)\n .build();\n\nIn this case, the system computes location roughly every ten minutes and\ndelivers approximately six location data points in a batch approximately every\nhour. While you still get location updates every ten minutes or so, you conserve\nbattery because your device wakes up only every hour or so.\n\nUse passive location updates\n----------------------------\n\nIn background use cases, it is a good idea to throttle location updates. Android\n8.0 (API level 26) limits enforce this practice, but apps running on lower\ndevices should strive to limit background location as much as possible.\n\nIt is likely that while your app is in the background, another app may be\nfrequently requesting location updates in the foreground. Location services\nmakes these updates available to your app. Consider the following location\nrequest, which opportunistically consumes location data: \n\n### Kotlin\n\n val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 15 * 60 * 1000)\n .setMinUpdateIntervalMillis(2 * 60 * 1000)\n .build()\n\n### Java\n\n LocationRequest request = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 15 * 60 * 1000)\n .setMinUpdateIntervalMillis(2 * 60 * 1000)\n .build();\n\nIn the previous example, the app's location computes roughly every 15 minutes.\nIf other apps request location, the app receives the data at a maximum interval\nof two minutes.\n\nWhile consuming location passively incurs no battery drain, take extra care in\ncases where the receipt of location data triggers expensive CPU or I/O\noperations. To minimize battery costs, the interval specified in\n[`setMinUpdateIntervalMillis()`](https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.Builder#public-locationrequest.builder-setmaxupdateagemillis-long-maxupdateagemillis(long)) shouldn't be too small."]]