이 예제에서는 Android에서 현재 연결된 Wi-Fi 네트워크의 ID(Network ID)를 가져오는 방법을 단계별로 살펴보겠습니다.
개요
Wi-Fi 네트워크 ID는 기기에 저장된 Wi-Fi 네트워크 설정을 식별하는 고유한 정수 값입니다. WifiManager와 WifiInfo 클래스를 활용하면 현재 연결된 네트워크의 ID를 손쉽게 조회할 수 있습니다.
구현 단계
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>위 코드에서는 Wi-Fi 네트워크 ID를 화면에 표시하기 위해 TextView를 사용했습니다.
3단계 — MainActivity 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
textView.setText("" + wifiInfo.getNetworkId());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}핵심 로직은 getSystemService(WIFI_SERVICE)를 통해 WifiManager 인스턴스를 얻고, getConnectionInfo()로 현재 Wi-Fi 연결 정보를 가져온 뒤, getNetworkId() 메서드로 네트워크 ID를 조회하는 것입니다.
4단계 — 매니페스트 권한 설정
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_WIFI_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" />
<action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>여기서 가장 중요한 부분은 ACCESS_WIFI_STATE 권한입니다. 이 권한이 선언되어 있지 않으면 Wi-Fi 상태 정보에 접근할 수 없으므로 반드시 추가해야 합니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 휴대폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바에서 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 해당 기기에 앱이 설치되어 실행됩니다.
앱이 정상적으로 실행되면 화면에 현재 연결된 Wi-Fi 네트워크의 ID가 숫자 형태로 표시됩니다.
