Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีดึง Network ID ของ Wi-Fi ปัจจุบันใน Android

บทนำ

ตัวอย่างนี้สาธิตวิธีดึง Network ID ของการเชื่อมต่อ Wi-Fi ปัจจุบัน โดย Network ID เป็นตัวระบุเฉพาะ (Integer) ของแต่ละ Wi-Fi Network Configuration ที่บันทึกไว้ในระบบ

ขั้นตอนที่ 1: สร้างโปรเจกต์

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: 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:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (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();
        
        // ดึง Network ID (Integer) ของ Wi-Fi Configuration ที่เชื่อมต่ออยู่
        textView.setText("" + wifiInfo.getNetworkId());
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}

ขั้นตอนที่ 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>

ผลลัพธ์

วิธีดึง Network ID ของ Wi-Fi ปัจจุบันใน Android

WifiInfo Fields สำคัญ (Cheat Sheet)

เมธอด คืนค่า คำอธิบาย
getNetworkId()intID ของ Wi-Fi Configuration ในระบบ (-1 หากไม่ได้เชื่อมต่อ)
getSSID()Stringชื่อเครือข่าย (มี quotes เช่น "MyWiFi")
getBSSID()StringMAC Address ของ Access Point
getMacAddress()StringMAC Address ของอุปกรณ์ (Randomized Android 6+)
getIpAddress()intIPv4 Packed Integer (ใช้ Formatter.formatIpAddress)
getLinkSpeed()intLink Speed (Mbps)
getRssi()intSignal Strength (dBm, negative)
getFrequency()intChannel Frequency (MHz)
getHiddenSSID()booleanHidden Network หรือไม่

การใช้งาน Network ID

  • WifiManager.enableNetwork(netId, true): บังคับเชื่อมต่อ Network ID นั้น
  • WifiManager.disableNetwork(netId): ปิดการเชื่อมต่อ Network ID นั้น
  • WifiManager.removeNetwork(netId): ลบ Configuration นั้นออก
  • WifiManager.getConfiguredNetworks(): ดูรายการ Network ทั้งหมดที่บันทึกไว้

ข้อจำกัด Android 10+ (Privacy)

  • ต้องการ ACCESS_FINE_LOCATION หรือ ACCESS_COARSE_LOCATION
  • Android 12+ ต้องเป็น Foreground App
  • บาง Device/ROM อาจคืนค่า -1 หรือค่าคงที่เสมอ

โค้ดปลอดภัย (Null Check + Permission)

private void fetchNetworkId() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        
        WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wifiMgr != null) {
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                int netId = wifiInfo.getNetworkId();
                textView.setText(netId != -1 ? "Network ID: " + netId : "Not connected to Wi-Fi");
            }
        }
    } else {
        ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
    }
}