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

วิธีปิด Wi-Fi ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีปิด Wi-Fi ผ่านโปรแกรมโดยใช้ WifiManager.setWifiEnabled(false) หมายเหตุสำคัญ: ตั้งแต่ Android 10 (API 29) ไม่สามารถเปิด/ปิด Wi-Fi โดยตรงผ่านโปรแกรมได้แล้ว ต้องนำทางผู้ใช้ไปที่ Settings

ขั้นตอนการสร้างโปรเจกต์

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

Android Studio → File → New Project → Empty Activity

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

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center"
        android:padding="16dp"
        android:text="สถานะ Wi-Fi: กำลังตรวจสอบ..." />

    <Button
        android:id="@+id/btnToggleWifi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ปิด/เปิด Wi-Fi"
        android:layout_marginTop="16dp" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (src/MainActivity.java)

package com.example.myapplication;

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.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Button btnToggleWifi;
    WifiManager wifiManager;

    @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);
        btnToggleWifi = findViewById(R.id.btnToggleWifi);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

        updateWifiStatus();

        btnToggleWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleWifi();
            }
        });
    }

    private void updateWifiStatus() {
        if (wifiManager != null) {
            boolean isEnabled = wifiManager.isWifiEnabled();
            textView.setText("สถานะ Wi-Fi: " + (isEnabled ? "เปิด (ON)" : "ปิด (OFF)"));
        }
    }

    private void toggleWifi() {
        if (wifiManager == null) {
            Toast.makeText(this, "ไม่รองรับ Wi-Fi", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean currentlyEnabled = wifiManager.isWifiEnabled();
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10 (API 29) + : ไม่อนุญาตให้แอปสลับ Wi-Fi โดยตรง
            Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
            startActivity(intent);
            Toast.makeText(this, "กรุณาสลับ Wi-Fi ในการตั้งค่า", Toast.LENGTH_LONG).show();
        } else {
            // Android 9 (API 28) และก่อนหน้า: สลับได้โดยตรง
            boolean success = wifiManager.setWifiEnabled(!currentlyEnabled);
            if (success) {
                Toast.makeText(this, "กำลัง" + (!currentlyEnabled ? "เปิด" : "ปิด") + " Wi-Fi...", Toast.LENGTH_SHORT).show();
                // รอสักครู่แล้วอัปเดต UI
                textView.postDelayed(this::updateWifiStatus, 1000);
            } else {
                Toast.makeText(this, "สลับ Wi-Fi ไม่สำเร็จ (อาจไม่มี Permission)", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml - Permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <!-- สำหรับ Android 9 และก่อนหน้า -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <!-- สำหรับ Android 10+ (API 29+) - ไม่จำเป็นสำหรับแค่เปิด Settings -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- สำหรับ Scan -->

    <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>

สรุปการเปลี่ยนแปลงตาม API Level (Wi-Fi Control)

API LevelAndroid VersionWifiManager.setWifiEnabled()วิธีที่แนะนำ
< 29Android 9 (Pie) และก่อนทำงานได้ (ต้อง CHANGE_WIFI_STATE)โค้ดโดยตรง
29 (Q)Android 10Deprecated/No-op (คืนค่า false เสมอ)Intent → Settings
>= 30 (R)Android 11+Removed/No-opIntent → Settings / Wi-Fi Suggestion API

Wi-Fi Suggestion API (Android 10+ แทนการควบคุมตรง)

Android 10+ แนะนำให้ใช้ WifiNetworkSuggestion เพื่อแนะนำเครือข่าย Wi-Fi ให้ผู้ใช้เลือกเชื่อมต่อ เอง ไม่บังคับ:

// Android 10+ (API 29+)
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

List<WifiNetworkSuggestion> suggestions = new ArrayList<>();
suggestions.add(new WifiNetworkSuggestion.Builder()
    .setSsid("MyHomeWiFi")
    .setWpa2Passphrase("password123")
    .setPriority(10)
    .build());

int status = wifiManager.addNetworkSuggestions(suggestions);
if (status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
    // ระบบจะแจ้งเตือนผู้ใช้ให้เชื่อมต่อ
}

ข้อควรระวัง

  • Android 10+: Google จำกัดสิทธิ์การควบคุม Radio (Wi-Fi, Bluetooth) เพื่อความเป็นส่วนตัว
  • แอป System/Pre-installed/Device Owner/Carrier Privileged เท่านั้นที่ยังควบคุมตรงได้
  • ใช้ ACTION_WIFI_SETTINGS หรือ ACTION_WIRELESS_SETTINGS นำทางผู้ใช้
  • Permission CHANGE_WIFI_STATE ยังคงต้องประกาศแต่ไม่ทำงานบน API 29+
  • สำหรับ Enterprise/Managed Devices ใช้ Device Policy Manager (DevicePolicyManager.setWifiEnabled)