이 튜토리얼에서는 Geocoder와 LocationManager를 활용해 안드로이드 앱에서 현재 위치 기반의 국가 이름을 가져오고, 이를 원하는 값으로 변경하여 화면에 표시하는 방법을 단계별로 알아봅니다.
핵심 개념 이해하기
안드로이드에서 국가 이름은 일반적으로 GPS 또는 네트워크 위치 정보를 Geocoder로 역지오코딩(Reverse Geocoding)하여 얻습니다. 이 예제에서는 가져온 주소 객체의 setCountryName() 메서드를 사용해 국가 이름을 임의의 값으로 변경한 뒤 화면에 출력합니다.
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:textSize="30sp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
위 코드에서는 국가 이름 정보를 화면에 표시하기 위한 TextView 하나를 배치했습니다. 텍스트 크기는 30sp로 설정되어 있어 결과를 쉽게 확인할 수 있습니다.
3단계: MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textView;
Location location;
double describeContents;
List<Address> addresses;
Geocoder geocoder;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
geocoder= new Geocoder(this);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
Address address = addresses.get(0);
address.setCountryName("London");
textView.setText("" + address.getCountryName());
} catch (IOException e) {
e.printStackTrace();
}
} else {
//not granted
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
Address address = addresses.get(0);
address.setCountryName("London");
textView.setText("" + address.getCountryName());
} catch (IOException e) {
e.printStackTrace();
}
}
}코드 동작 방식 살펴보기
위 코드의 핵심 흐름은 다음과 같습니다.
① 권한 요청: onCreate()에서 위치 서비스 매니저를 초기화하고, 정밀 위치(ACCESS_FINE_LOCATION)와 대략적 위치(ACCESS_COARSE_LOCATION) 권한이 없으면 사용자에게 권한을 요청합니다.
② 마지막 위치 가져오기: getLastKnownLocation(NETWORK_PROVIDER)를 호출해 네트워크 기반의 마지막 알려진 위치를 얻고, Geocoder 인스턴스를 생성합니다.
③ 주소 변환 및 국가 이름 변경: 권한이 승인되면 getFromLocation()으로 좌표를 주소 목록으로 변환합니다. 그런 다음 첫 번째 주소 객체에서 setCountryName("London")을 호출해 국가 이름을 "London"으로 변경하고, getCountryName()으로 값을 읽어와 TextView에 표시합니다.
④ 결과 처리: onResume()에서도 동일한 로직을 수행하여 화면이 다시 활성화될 때 최신 정보를 반영하도록 했습니다.
4단계: AndroidManifest.xml 설정
AndroidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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>
</application>
</manifest>매니페스트에는 위치 정보 접근을 위한 ACCESS_COARSE_LOCATION, Geocoder의 온라인 조회를 위한 INTERNET, 그리고 READ_PHONE_STATE 권한을 선언했습니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 본인의 모바일 기기를 선택하면, 앱이 설치되어 실행됩니다.
앱이 실행되면 위치 권한 허용 여부를 묻는 대화상자가 나타나며, 권한을 허용하면 화면에 변경된 국가 이름("London")이 표시됩니다.

참고 사항
실제 프로젝트에서는 다음 사항을 유의하세요.
- getLastKnownLocation()은 null을 반환할 수 있으므로 실무에서는 null 체크를 추가하는 것이 좋습니다.
- Geocoder는 백그라운드 스레드에서 호출하는 것이 권장되며, 기기에 백엔드 서비스가 없는 경우 IOException이 발생할 수 있습니다.
- setCountryName()으로 변경한 값은 해당 Address 객체에만 적용되며, 시스템 설정의 실제 국가 설정을 바꾸는 것은 아닙니다.