[2025年5月最新版]Androidアプリで位置情報を取得する方法

位置情報を取得する|Android開発で記述したLocationRequest.create()deprecatedになっていたので、その対処方法です。
現在はLocationRequest.Builderを使用してLocationRequestを構築することが推奨されています。

  • 対象AndroidSDK: 35

権限の追加

AndroidManifest.xmlに次の権限を追加します。(これまでと変更なし)

<!-- 位置情報 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 位置情報 正確な情報が欲しい場合に追加で指定する -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

依存関係の追加

ライブラリはコードを記入後、Android Studioでマウスカーソルをあてると、次のようなポップアップが表示されるので、Add dependency on…をクリックすると、依存関係の追加が行われ、importもできるようになります。

依存関係の追加

依存関係の追加により、以下のファイルに変更が加わります。

app\build.gradle.kts

dependenciesに以下が追加されます。

dependencies {
    implementation(libs.play.services.location)
}

gradle\libs.versions.toml

gradle\libs.versions.tomlにも次のような行が追加されます。

[libraries]
play-services-location = { group = "com.google.android.gms", name = "play-services-location", version.ref = "playServicesLocation" }

ソースコードの変更

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
        .addLocationRequest(new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1000).build());

上記でLocationRequest.Builder()に指定しているパラメータPRIORITY_HIGH_ACCURACYは可能な限り最も高精度の位置情報をリクエストする設定です。また、1000ミリ秒(1秒)間隔での受信を設定しています。
変更後のソースは次のようになります。

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
        .addLocationRequest(new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1000).build());

SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
    @Override
    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
        // 位置情報の設定がONの場合
    }
});

task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        if (e instanceof ResolvableApiException) {
            // 位置情報の設定がOFFの場合
        }
    }
});

設定画面を現在推奨されるActivityResult APIで起動する方法

位置情報の設定画面起動についても、ResolvableApiExceptionstartResolutionForResult()を使用する方法ではなく、新しい方法が推奨されています。

ActivityResultLauncherのメンバ変数を用意し、onCreate()で生成します。

private ActivityResultLauncher<IntentSenderRequest> _resolutionLauncher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // 省略...

    this._resolutionLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    // 位置情報の設定をONにした場合の処理
                }
            }
    );
}

onFailure()では次のようにして、位置情報の設定要求を行います。

@Override
public void onFailure(@NonNull Exception e) {
    if (e instanceof ResolvableApiException) {
        try {
            ResolvableApiException resolvable = (ResolvableApiException) e;
            IntentSender intentSender = resolvable.getResolution().getIntentSender();
            IntentSenderRequest senderRequest = new IntentSenderRequest.Builder(intentSender).build();

            MainActivity.this._resolutionLauncher.launch(senderRequest);
        } catch (Exception sendEx) {
            Toast.makeText(getBaseContext(), "位置情報をONにしてください。", Toast.LENGTH_SHORT).show();
        }
    }
}

権限リクエスト

権限リクエストの方法も記載しておきます。

定義値

private static final int PERMISSION_REQUEST_CODE = 10;

private String[] _permissions = new String[] {
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION
};

権限チェックメソッド

必要な権限が許可されているかどうかをチェックするメソッドです。

private boolean allPermissionsGranted() {
    for (String permission : this._permissions) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED)
            return false;
    }
    return true;
}

権限チェックの実施

onCreate()など任意のタイミングで権限チェックメソッドをコールし、権限が不足している場合は権限のリクエストを行います。

if (allPermissionsGranted()) {
    // すべての権限が許可されている場合
    // 上記の設定画面チェックなどを行う
} else {
    ActivityCompat.requestPermissions(this, this._permissions, PERMISSION_REQUEST_CODE);
}

権限リクエストの結果受信

権限リクエストの結果を受け取るメソッドをActivityに追加します。

@SuppressLint("MissingSuperCall")
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (allPermissionsGranted()) {
            // すべての権限が許可されている場合
            // 上記の設定画面チェックなどを行う
        } else {
            finish();
        }
    }
}

位置情報を取得する

位置情報の取得もLocationRequest.Builderを使用する方法に変更します。

private void startLocationUpdates() {
    LocationRequest.Builder builder = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1000);

    try {
        this._fusedLocationClient.requestLocationUpdates(builder.build(), this._locationCallback, Looper.getMainLooper());
    } catch (SecurityException unlikely) {
        Log.e("Location", "Lost location permission. Could not request updates. " + unlikely);
    }
}

_fusedLocationClient_locationCallbackonCreate()などで生成します。_locationCallbackonLocationResult()メソッドは位置情報更新を受け取るコールバックメソッドです。

private FusedLocationProviderClient _fusedLocationClient;
private LocationCallback _locationCallback;

@Override
protected void onCreate(Bundle savedInstanceState) {
  // 省略...

    this._locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            super.onLocationResult(locationResult);

            Location lastLocation = locationResult.getLastLocation();
            if (lastLocation == null) return;
            Log.i("LastLocation", String.format("%f, %f", lastLocation.getLatitude(), lastLocation.getLongitude()));
        }
    };
    this._fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

位置情報の更新を停止する

this._fusedLocationClient.removeLocationUpdates(this._locationCallback);

参考

このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です