直近の現在地情報を取得する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
アプリでは、Google Play 開発者サービスの位置情報 API を使用して、ユーザーのデバイスの直近の位置情報をリクエストできます。ほとんどの場合、アプリが必要とする位置情報はユーザーの現在地です。通常、これはデバイスが最後に確認された場所に対応します。
デバイスの直近の位置情報を取得するには、融合された位置予測プロバイダを使用します。融合された位置予測プロバイダは Google Play 開発者サービスの位置情報 API の 1 つです。基盤となる位置情報テクノロジーを管理し、高精度や省電力といったハイレベルの要件を指定できるシンプルな API を提供します。また、デバイスの電池の消費を最適化します。
注: アプリがバックグラウンドで実行される場合、位置情報へのアクセスがアプリの中核的機能にとって必要不可欠であることと、位置情報へのアクセスをユーザーに適切に開示することが要件として求められます。
このレッスンでは、融合された位置予測プロバイダの getLastLocation()
メソッドを使用して、デバイスの位置情報を 1 回だけリクエストする方法を説明します。
Google Play 開発者サービスのセットアップ
融合された位置予測プロバイダにアクセスするには、アプリの開発プロジェクトに Google Play 開発者サービスが含まれている必要があります。Google Play 開発者サービスのコンポーネントを SDK Manager でダウンロードしてインストールし、ライブラリをプロジェクトに追加します。詳細については、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()
メソッドは、地理的位置の緯度と経度の座標を含む Location
オブジェクトの取得に使用できる Task
を返します。位置情報オブジェクトは、次の状況では null
になる可能性があります。
- デバイスの設定で位置情報がオフになっている。位置情報を無効にするとキャッシュも削除されるため、直近の位置情報が以前に取得されていても、結果が
null
になる可能性があります。
- デバイスが位置情報を記録していなかった。このケースは、新しいデバイスまたは出荷時の設定に戻されたデバイスで起きる可能性があります。
- デバイスで Google Play 開発者サービスが再起動されたが、サービスの再起動後に位置情報をリクエストしたアクティブな融合された位置予測プロバイダ クライアントが存在しなかった。この状況を回避するには、新しいクライアントを作成して、独自に位置情報の更新データをリクエストします。詳細については、位置情報の更新をリクエストするをご覧ください。
位置情報の最良推定値を選択する
FusedLocationProviderClient
には、デバイスの位置情報を取得するためのメソッドがいくつか用意されています。アプリのユースケースに応じて、次のいずれかを選択します。
getLastLocation()
は、位置情報の推定値をよりすばやく取得し、アプリに関連するバッテリー使用量を最小限に抑えます。ただし、直近で他のクライアントが位置情報をアクティブに使用していない場合は、位置情報が最新でない可能性があります。
getCurrentLocation()
は、より新しく正確な位置情報をより頻繁に取得します。ただし、このメソッドを使用すると、デバイス上でアクティブな位置情報の計算が行われる可能性があります。
これは、新しい位置情報を取得する場合に可能な限り推奨される方法であり、requestLocationUpdates()
を使用してご自身で位置情報の更新を開始、管理するなどの他の方法よりも安全です。アプリで requestLocationUpdates()
を呼び出すと、位置情報が利用できない場合、または新しい位置情報の取得後にリクエストが正しく停止されない場合に、大量の電力を消費することがあります。
参考情報
Android で現在地を取得する方法について詳しくは、次の資料をご覧ください。
サンプル
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-08-21 UTC。
[null,null,["最終更新日 2025-08-21 UTC。"],[],[],null,["# Get the last known location\n\nUsing 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---------------------------\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-----------------------\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-------------------------------\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\n### Kotlin\n\n```kotlin\nprivate lateinit var fusedLocationClient: FusedLocationProviderClient\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)\n}\n```\n\n### Java\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---------------------------\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\n### Kotlin\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\n### Java\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---------------------------------\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--------------------\n\nFor more information about fetching current location in Android, view the\nfollowing materials:\n\n### Samples\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."]]