取得最後已知位置
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
應用程式可透過 Google Play 服務 Location API,要求取得使用者裝置的最後已知位置。多數情況下,您會關注使用者目前的位置,通常相當於裝置的最後已知位置。
具體來說,請使用整合式位置預測提供工具,來擷取裝置的最後已知位置。整合式位置預測提供工具是 Google Play 服務中的其中一項 Location API。該服務可管理基本的位置技術,並提供簡易 API,方便您指定高層級的要求,例如高準確度或低功耗。此外還會最佳化裝置的電池用量。
注意:應用程式在背景中執行時,存取位置資訊應對對應用程式的核心功能至關重要,同時必須適當地向使用者揭露。
本課程說明如何使用整合式位置預測提供工具中的 getLastLocation()
方法,來對裝置的位置發出單一請求。
設定 Google Play 服務
如要存取整合式位置預測提供工具,應用程式的開發專案必須包含 Google Play 服務。透過 SDK Manager 下載並安裝 Google Play 服務元件,然後將程式庫新增至專案。詳情請參閱設定 Google Play 服務指南
指定應用程式權限
如果應用程式功能使用定位服務,必須要求位置存取權 (視這些功能的用途而定)。
建立定位服務用戶端
在活動的 onCreate()
方法中,如以下程式碼片段所示,建立整合式位置預測提供工具用戶端的執行個體。
Kotlin
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
Java
private FusedLocationProviderClient fusedLocationClient;
// ..
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
取得最後已知位置
建立「定位服務」用戶端後,即可取得使用者裝置的最後已知位置。將應用程式連線至這些用戶端後,即可使用整合式位置預測提供工具的 getLastLocation()
方法來擷取裝置位置。此呼叫傳回的位置準確度取決於您在應用程式資訊清單中進行的權限設定,詳情請參閱如何要求位置存取權的指南。
如要要求最後已知位置,請呼叫 getLastLocation()
方法。下列程式碼片段會說明要求,以及簡單的回應處理方式:
Kotlin
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location. In some rare situations this can be null.
}
Java
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
getLastLocation()
方法會傳回 Task
,您可以用於取得 Location
物件,並包含地理位置的經緯度座標。在以下情況中,位置物件可能是 null
:
- 定位服務在裝置設定中已關閉。即使最後位置是先前擷取的,系統仍會將其設為
null
,因為停用定位服務也會清除快取。
- 裝置並未記錄其位置資訊,例如新裝置或已還原至原廠設定的裝置。
- 裝置上的 Google Play 服務已重新啟動,且在服務重新啟動後,並未啟用要求定位服務的整合式位置預測提供工具用戶端。如要避免這種情況發生,您可以建立新用戶端,並自行要求位置更新通知。詳情請參閱「要求位置更新通知」。
選擇最佳位置預測結果
FusedLocationProviderClient
提供多種方法來擷取裝置位置資訊。視應用程式的用途而定,從下方選擇其中一項:
getLastLocation()
會更快取得位置資訊的預測結果,並盡量減少可能歸因於應用程式的電池用量。但如果最近沒有其他用戶端經常使用位置資訊,則位置資訊可能已經過時。
getCurrentLocation()
會取得更穩定準確的新位置。然而,這個方法可能會導致裝置的有效位置計算功能
這是盡可能取得最新位置的建議方式,而且使用 requestLocationUpdates()
來自行啟動和管理位置更新比其他方法更安全。如果應用程式呼叫 requestLocationUpdates()
,當應用程式無法取得位置資訊,或是取得新位置資訊後無法正確停止要求,有時可能會耗用大量電力。
其他資源
如要進一步瞭解如何在 Android 中擷取目前位置,請參閱下列資料:
範例
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-21 (世界標準時間)。
[null,null,["上次更新時間:2025-08-21 (世界標準時間)。"],[],[],null,["Using the Google Play services location APIs, your app can request the last\nknown location of the user's device. In most cases, you are interested in the\nuser's current location, which is usually equivalent to the last known\nlocation of the device.\n\nSpecifically, use the\n[fused\nlocation provider](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html) to retrieve the device's last known location. The fused\nlocation provider is one of the location APIs in Google Play services. It\nmanages the underlying location technology and provides a simple API so that\nyou can specify requirements at a high level, like high accuracy or low power.\nIt also optimizes the device's use of battery power. \n**Note:** When your app is running in the background,\n[access to location](/training/location/background) should be\ncritical to the core functionality of the app and is accompanied with proper\ndisclosure to users.\n\nThis lesson shows you how to make a single request for the location of a\ndevice using the\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod in the fused location provider.\n\nSet up Google Play services\n\nTo access the fused location provider, your app's development project must\ninclude Google Play services. Download and install the Google Play services\ncomponent via the [SDK\nManager](/tools/help/sdk-manager) and add the library to your project. For details, see the guide to\n[Setting Up Google Play\nServices](/google/play-services/setup).\n\nSpecify app permissions\n\nApps whose features use location services must\n[request location permissions](/training/location/permissions),\ndepending on the use cases of those features.\n\nCreate location services client\n\nIn your activity's [onCreate()](/reference/android/app/Activity#onCreate(android.os.Bundle)) method,\ncreate an instance of the Fused Location Provider Client as the following code snippet shows. \n\nKotlin \n\n```kotlin\nprivate lateinit var fusedLocationClient: FusedLocationProviderClient\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)\n}\n```\n\nJava \n\n```java\nprivate FusedLocationProviderClient fusedLocationClient;\n\n// ..\n\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);\n}\n```\n\nGet the last known location\n\nOnce you have created the Location Services client\nyou can get the last known location of a user's device. When your app is\nconnected to these you can use the fused location provider's\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod to retrieve the device location. The precision of the location returned\nby this call is determined by the permission setting you put in your app\nmanifest, as described in the guide on how to\n[request location permissions](/training/location/permissions).\n\nTo request the last known location, call the\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod. The following code snippet illustrates the request and a simple handling of the\nresponse: \n\nKotlin \n\n```kotlin\nfusedLocationClient.lastLocation\n .addOnSuccessListener { location : Location? -\u003e\n // Got last known location. In some rare situations this can be null.\n }\n```\n\nJava \n\n```java\nfusedLocationClient.getLastLocation()\n .addOnSuccessListener(this, new OnSuccessListener\u003cLocation\u003e() {\n @Override\n public void onSuccess(Location location) {\n // Got last known location. In some rare situations this can be null.\n if (location != null) {\n // Logic to handle location object\n }\n }\n });\n```\n\nThe\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod returns a [`Task`](https://developers.google.com/android/reference/com/google/android/gms/tasks/Task)\nthat you can use to get a\n[`Location`](/reference/android/location/Location)\nobject with the latitude and longitude coordinates of a\ngeographic location. The location object may be `null` in the\nfollowing situations:\n\n- Location is turned off in the device settings. The result could be `null` even if the last location was previously retrieved because disabling location also clears the cache.\n- The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.\n- Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see [Request location\n updates](/training/location/receive-location-updates).\n\nChoose the best location estimate\n\nThe `FusedLocationProviderClient` provides several methods to retrieve device\nlocation information. Choose from one of the following, depending on your app's\nuse case:\n\n- [`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getLastLocation()) gets a location estimate more quickly and minimizes battery usage that can be attributed to your app. However, the location information might be out of date, if no other clients have actively used location recently.\n- [`getCurrentLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken))\n gets a fresher, more accurate location more consistently. However, this method\n can cause active location computation to occur on the device\n\n This is the recommended way to get a fresh location, whenever possible, and\n is safer than alternatives like starting and managing location updates\n yourself using `requestLocationUpdates()`. If your app calls\n `requestLocationUpdates()`, your app can sometimes consume large amounts of\n power if location isn't available, or if the request isn't stopped correctly\n after obtaining a fresh location.\n\nAdditional resources\n\nFor more information about fetching current location in Android, view the\nfollowing materials:\n\nSamples\n\n- [Sample app](https://github.com/android/platform-samples/tree/main/samples/location/src/main/java/com/example/platform/location/currentLocation) to demonstrate best practices while fetching current location."]]