이 튜토리얼에서는 안드로이드에서 네트워크 프로바이더(Network Provider)를 활용해 현재 위치의 우편번호를 가져오는 방법을 단계별로 알아봅니다. Geocoder 클래스와 LocationManager를 함께 사용하면 위도·경도 정보를 실제 주소의 우편번호로 변환할 수 있습니다.
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성 (activity_main.xml)
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 하나를 배치했습니다.
3단계: 메인 액티비티 구현 (MainActivity.java)
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);
textView.setText("" + address.getPostalCode());
} catch (IOException e) {
e.printStackTrace();
}
} else {
//권한이 허용되지 않은 경우
}
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);
textView.setText("" + address.getPostalCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}위 코드의 핵심 동작 흐름은 다음과 같습니다.
- getLastKnownLocation(NETWORK_PROVIDER): 네트워크 프로바이더(Wi-Fi 또는 셀룰러 기지국) 기반으로 마지막으로 확인된 위치를 가져옵니다.
- Geocoder.getFromLocation(): 얻어낸 위도와 경도를 실제 주소 목록으로 변환합니다.
- getPostalCode(): 변환된 주소 객체에서 우편번호 값을 추출해 TextView에 표시합니다.
또한 위치 권한(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION)이 부여되지 않은 경우 런타임에 권한 요청 다이얼로그를 띄우고, 결과를 onRequestPermissionsResult() 콜백에서 처리하도록 구현했습니다.
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은 대략적인 위치 접근 권한, INTERNET은 Geocoder가 온라인으로 주소를 조회하는 데 필요한 권한입니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run
아이콘을 클릭하세요. 실행 옵션에서 본인의 모바일 기기를 선택하면, 기기 화면에 현재 위치의 우편번호가 표시됩니다.

참고: Geocoder는 백엔드 서비스에 의존하므로 일부 기기나 지역에서는 결과가 반환되지 않을 수 있습니다. 이 경우 null 체크와 예외 처리를 보강하고, Google Play Services의 FusedLocationProviderClient 사용도 함께 고려해 보시기 바랍니다.