Androidでユーザーの現在地を取得する最も簡単な方法【完全ガイド】
この記事では、Androidアプリでユーザーの現在地を取得する最もシンプルな方法を、ステップごとに詳しく解説します。Google Play ServicesのFusedLocationProviderClientを使用し、位置情報だけでなく、Geocoderを使って住所や都市名まで表示するサンプルアプリを作成します。
全体の流れ
実装は以下の手順で進めます。
- Android Studioで新規プロジェクトを作成する
- レイアウトファイル(activity_main.xml)を編集する
- Gradleに依存関係を追加する
- MainActivity.javaを実装する
- GetAddressIntentService.javaを作成する
- AndroidManifest.xmlに権限とサービスを登録する
ステップ1:新規プロジェクトの作成
まず、Android Studioを開き、「File」→「New Project」から新しいプロジェクトを作成します。Empty Activityテンプレートを選択し、必要な情報を入力してプロジェクトを生成してください。言語はJavaを選択します。
ステップ2:レイアウトファイルの編集
res/layout/activity_main.xml に以下のコードを追加します。画面上部にタイトル用のTextView、中央に現在地の住所を表示するTextViewを配置しています。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Current Location and City Name"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"/>
</RelativeLayout>
ステップ3:Gradleへの依存関係の追加
app/build.gradle の dependencies ブロックに、Google Play Servicesの位置情報ライブラリを追加します。これによりFusedLocationProviderClientが使用可能になります。
implementation 'com.google.android.gms:play-services-location:17.0.0'
※最新版のライブラリではLocationRequestの生成方法がBuilderパターンに変更されているため、環境に応じて適宜読み替えてください。
ステップ4:MainActivity.javaの実装
src/MainActivity.java に以下のコードを記述します。このクラスでは、位置情報の権限チェック、位置情報の定期取得、そして取得した座標をもとに住所変換サービスを起動する処理を行います。
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationClient;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 2;
private LocationAddressResultReceiver addressResultReceiver;
private TextView currentAddTv;
private Location currentLocation;
private LocationCallback locationCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressResultReceiver = new LocationAddressResultReceiver(new Handler());
currentAddTv = findViewById(R.id.textView);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
currentLocation = locationResult.getLocations().get(0);
getAddress();
}
};
startLocationUpdates();
}
@SuppressWarnings("MissingPermission")
private void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
else {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(2000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
}
@SuppressWarnings("MissingPermission")
private void getAddress() {
if (!Geocoder.isPresent()) {
Toast.makeText(MainActivity.this, "Can't find current address.",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(this, GetAddressIntentService.class);
intent.putExtra("add_receiver", addressResultReceiver);
intent.putExtra("add_location", currentLocation);
startService(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull
int[] grantResults) {
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
}
else {
Toast.makeText(this, "Location permission not granted. Restart the app if you want the
feature", Toast.LENGTH_SHORT).show();
}
}
}
private class LocationAddressResultReceiver extends ResultReceiver {
LocationAddressResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == 1) {
Toast.makeText(MainActivity.this, "Address not found.", Toast.LENGTH_SHORT).show();
}
String currentAdd = resultData.getString("address_result");
showResults(currentAdd);
}
}
private void showResults(String currentAdd) {
currentAddTv.setText(currentAdd);
}
@Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
@Override
protected void onPause() {
super.onPause();
fusedLocationClient.removeLocationUpdates(locationCallback);
}
}
ポイント:onResume()で位置情報の更新を開始し、onPause()で停止することで、バッテリー消費を抑えつつ、アプリが前面にある間だけ正確な位置情報を取得できます。
ステップ5:GetAddressIntentService.javaの作成
次に、緯度経度を住所に変換する(逆ジオコーディング)ためのサービスクラスを作成します。「New → Java Class」で GetAddressIntentService.java を作成し、以下のコードを記述してください。
package app.com.sample;
import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import androidx.annotation.Nullable;
public class GetAddressIntentService extends IntentService {
private static final String IDENTIFIER = "GetAddressIntentService";
private ResultReceiver addressResultReceiver;
public GetAddressIntentService() {
super(IDENTIFIER);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String msg;
addressResultReceiver = Objects.requireNonNull(intent).getParcelableExtra("add_receiver");
if (addressResultReceiver == null) {
Log.e("GetAddressIntentService", "No receiver, not processing the request further");
return;
}
Location location = intent.getParcelableExtra("add_location");
if (location == null) {
msg = "No location, can't go further without location";
sendResultsToReceiver(0, msg);
return;
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (Exception ioException) {
Log.e("", "Error in getting address for the location");
}
if (addresses == null || addresses.size() == 0) {
msg = "No address found for the location";
sendResultsToReceiver(1, msg);
}
else {
Address address = addresses.get(0);
String addressDetails = address.getFeatureName() + "\n" + address.getThoroughfare() + "\n" +
"Locality: " + address.getLocality() + "\n" + "County: " + address.getSubAdminArea() + "\n" +
"State: " + address.getAdminArea() + "\n" + "Country: " + address.getCountryName() + "\n" +
"Postal Code: " + address.getPostalCode() + "\n";
sendResultsToReceiver(2, addressDetails);
}
}
private void sendResultsToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString("address_result", message);
addressResultReceiver.send(resultCode, bundle);
}
}
ポイント:Geocoderによる逆ジオコーディングはネットワーク通信を伴うため、メインスレッドではなくIntentService内で実行することで、ANR(アプリケーション応答なし)エラーを回避できます。
ステップ6:AndroidManifest.xmlの編集
最後に、androidManifest.xml に必要な権限とサービスの宣言を追加します。位置情報権限(ACCESS_FINE_LOCATION / ACCESS_COARSE_LOCATION)とインターネット権限が必要です。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GetAddressIntentService" />
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>
アプリの実行方法
それでは、アプリケーションを実行してみましょう。実際のAndroid端末をPCに接続していることを前提とします。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run
」アイコンをクリックします。次に、接続済みのモバイルデバイスをオプションから選択すると、アプリがインストールされ、画面が表示されます。
初回起動時には位置情報の利用許可を求めるダイアログが表示されるので、「許可」を選択してください。許可されると、数秒以内に現在の住所や都市名が画面中央に表示されます。
まとめ
本記事では、FusedLocationProviderClientによる現在地の取得と、Geocoder+IntentServiceによる住所変換の組み合わせを紹介しました。この構成は以下のメリットがあります。
- 省電力かつ高精度:FusedLocationProviderClientがGPS・Wi-Fi・基地局を自動的に使い分けます。
- UIの安定性:逆ジオコーディングをバックグラウンドサービスで行うため、画面が固まりません。
- ライフサイクル対応:onResume/onPauseで更新の開始・停止を制御し、無駄な電力消費を防ぎます。
なお、Android 10以降ではバックグラウンドでの位置情報取得に追加の制限があるほか、targetSdkVersion 31以降ではパーミッションの宣言方法にも変更があるため、最新の公式ドキュメントも併せて確認することをおすすめします。
-
【Android】プログラムからデバイスのIMEI/ESN番号を取得する方法
この記事では、AndroidアプリでプログラムからデバイスのIMEI/ESN番号を取得する方法を、実際のサンプルコードとともに段階的に解説します。IMEIは端末を一意に識別する重要な番号であり、取得にはユーザーの許可(パーミッション)が必要になる点にも注目してください。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(res/layout/activity_main.xml)にコー
-
Android端末のメインメールアドレスを取得する方法をサンプルコード付きで解説
本記事では、Android端末に登録されているメインのメールアドレスを取得する方法を、実際のサンプルコードとともにわかりやすく解説します。AccountManagerとGET_ACCOUNTS権限を活用することで、端末に設定されたアカウント情報からメールアドレスを取得できます。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを起動し、「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。 手順2:res/layout/activity_main.xml にコードを追加する 以下のコードをレイアウト