Android Wifi

Android Wifi

0.WifiManager API

创建 WIFI 的系统服务

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

检查 WIFI 状态

这个方法用于检查Wi-Fi是否当前已启用。如果Wi-Fi已启用,该方法将返回true;否则返回false。

boolean isWifiEnabled = wifiManager.isWifiEnabled();

关闭 WIFI

此方法用于启用或禁用Wi-Fi。参数enable指定是否启用Wi-Fi。调用此方法需要CHANGE_WIFI_STATE权限。

wifiManager.setWifiEnabled(false);

此外,WifiManager API还提供了丰富的方法来管理Wi-Fi连接,包括但不限于:

  • getWifiState :用于获取当前的Wi-Fi连接状态。可能的返回值包括WIFI_STATE_ENABLED(Wi-Fi已启用)、WIFI_STATE_DISABLING(Wi-Fi正在禁用)、WIFI_STATE_DISABLED(Wi-Fi已禁用)等。
  • getConnectionInfo:用于获取当前Wi-Fi的连接信息,通过该方法返回的WifiInfo对象,该对象包含了关于当前连接的详细信息,包括SSID、BSSID、网络ID、频率、信号强度等。
  • startScan :用于开始扫描周围的Wi-Fi信息。扫描结果可以通过注册SCAN_RESULTS_AVAILABLE_ACTION的广播接收器来获取。
  • getScanResults:用于获取Wi-Fi的扫描结果。
  • calculateSignalLevel:根据信号强度计算信号等级。
  • addNetworkenableNetworkdisableNetwork:用于添加、启用或禁用指定的Wi-Fi连接。
  • disconnect:用于断开当前的Wi-Fi连接。
  • reconnect:这个方法尝试重新连接到最近连接过的Wi-Fi网络。

1.权限申请

Android6.0之后需要动态申请权限。

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- //修改网络状态权限 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 修改wifi状态的权限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- //访问网络权限 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- //访问wifi权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 定位权限 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 改变wifi状态 -->

2.连接Wifi

public boolean connectWiFi(String ssid, String password) {
    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", ssid);
    wifiConfig.preSharedKey = String.format("\"%s\"", password);

    int netId = mWifiManager.addNetwork(wifiConfig);
    mWifiManager.disconnect();
    mWifiManager.enableNetwork(netId, true);
    return mWifiManager.reconnect();
}

3.断开Wifi

public void disconnectWifi(int netId) {
    mWifiManager.disableNetwork(netId);
    mWifiManager.disconnect();
}

4.切换Wifi

就是先断开,然后再连接

不走工具类,大概是这样的代码

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                WifiConfiguration wifiConfig = new WifiConfiguration();
                wifiConfig.SSID = "\"" + "a123" + "\""; // networkSSID是你想要连接的WiFi网络的SSID
                wifiConfig.preSharedKey = "\"" + "A123456" + "\""; // networkPass是该网络的密码
                int networkId = wifiManager.addNetwork(wifiConfig);
                List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
                for (int i = 0; i < configuredNetworks.size(); i++) {
                    if (configuredNetworks.get(i).SSID.equals("z9")) {
                        wifiManager.enableNetwork(configuredNetworks.get(i).networkId, false);
                        wifiManager.disableNetwork(configuredNetworks.get(i).networkId);
                        wifiManager.removeNetwork(configuredNetworks.get(i).networkId);
                        wifiManager.saveConfiguration();
                        wifiManager.disconnect();
                        break;
                    }
                    XLogUtils.d(configuredNetworks.get(i).SSID + "\t" + configuredNetworks.get(i).networkId);
                }
                wifiManager.updateNetwork(wifiConfig);
                wifiManager.enableNetwork(networkId, true);
                wifiManager.reconnect();

5.API28及以下的工具类

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;

import java.util.List;

/*
 * wifi管理
 * */
public class WifiUtils {

    // 定义WifiManager对象
    private final WifiManager mWifiManager;
    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表
    private List<ScanResult> mWifiList;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfiguration;
    // 定义一个WifiLock
    WifiManager.WifiLock mWifiLock;

    // 构造器
    public WifiUtils(Context context) {
        // 取得WifiManager对象
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 打开WIFI
    public WifiUtils openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
        return this;
    }

    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }
        return false;
    }

    // 关闭WIFI
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    // 检查当前WIFI状态
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock
    public void releaseWifiLock() {
        // 判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;
    }

    // 指定配置好的网络进行连接
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回
        if (index > mWifiConfiguration.size()) {
            return;
        }
        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
                true);
    }

    @SuppressLint("MissingPermission")
    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的网络连接
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到网络列表
    public List<ScanResult> getWifiList() {
        mWifiList = mWifiManager.getScanResults();
        return mWifiList;
    }

    // 查看扫描结果
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++) {
            stringBuilder
                    .append("Index_" + new Integer(i + 1).toString() + ":");
// 将ScanResult信息转换成一个字符串包
// 其中把包括:BSSID、SSID、capabilities、frequency、level
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID
    public String getName() {
        if (mWifiInfo == null) {
            return "NULL";
        }
        String name = mWifiInfo.getSSID();
        if (name.contains("\"")) {
            name = name.substring(1, name.length() - 1);
        }
        return name;
    }

    // 得到接入点的BSSID
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址
    public String getIPAddress() {
        return (mWifiInfo == null) ? "" : intToIp(mWifiInfo.getIpAddress());
    }

    // 将 wifiInfo.getIpAddress 转为IPV4的格式
    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    // 得到连接的ID
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    /**
     * 获取wifi加密方式
     */
    public String getEncrypt(ScanResult scanResult) {
        if (mWifiInfo != null) {
            String capabilities = scanResult.capabilities;
            if (!TextUtils.isEmpty(capabilities)) {
                if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                    return "WPA";
                } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                    return "WEP";
                } else {
                    return "没密码";
                }
            }
        }
        return "获取失败";
    }

    // 添加一个网络并连接
    public boolean addNetwork(WifiConfiguration wcg) {
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        System.out.println("a--" + wcgID);
        System.out.println("b--" + b);
        return b;
    }

    // 断开指定ID的网络
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    //连接指定wifi
    public boolean connectWiFi(String ssid, String password) {
        WifiConfiguration wifiConfig = new WifiConfiguration();
        wifiConfig.SSID = String.format("\"%s\"", ssid);
        wifiConfig.preSharedKey = String.format("\"%s\"", password);

        int netId = mWifiManager.addNetwork(wifiConfig);
        mWifiManager.disconnect();
        mWifiManager.enableNetwork(netId, true);
        return mWifiManager.reconnect();
    }

    //然后是一个实际应用方法,只验证过没有密码的情况:
    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if (Type == 1) //WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) //WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) //WIFICIPHER_WPA
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
//config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }


    @SuppressLint("MissingPermission")
    private WifiConfiguration IsExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    public String getPassWord() {
        String password = null;
        WifiConfiguration configuration = IsExsits(getName());
        if (configuration != null) {
            if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
                // WPA-PSK加密方式
                password = configuration.preSharedKey;
            } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) ||
                    configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
                // WPA/WPA2企业加密方式
                // 这里需要进一步处理,暂时忽略
                password = "企业网络,密码未知";
            } else if (configuration.wepKeys[0] != null) {
                // WEP加密方式
                password = configuration.wepKeys[0];
            }
        }
        return password;
    }

}

6.API29连接WiFi

主要有三种方式,P2P连接(NetworkRequest),suggestion建议连接,再就是两者的结合

6.1 P2P连接(NetworkRequest)

WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
                .setSsid("a88")
                .setWpa2Passphrase("Aa")
                .build();
        NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiNetworkSpecifier)
                .build();
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                connectivityManager.bindProcessToNetwork(network);
                connectivityManager.getNetworkInfo(network);
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                boolean connected = networkInfo.isConnected();
                boolean available = networkInfo.isAvailable();
                NetworkInfo.DetailedState detailedState = networkInfo.getDetailedState();
                Log.i("ConnectWifi", "onAvailable connected= " + connected);
                Log.i("ConnectWifi", "onAvailable available= " + available);
                Log.i("ConnectWifi", "onAvailable detailedState= " + detailedState);
            }

            @Override
            public void onUnavailable() {
                super.onUnavailable();
                Log.i("ConnectWifi", "onUnavailable 切换到指定wifi失败");
                connectivityManager.unregisterNetworkCallback(networkCallback);
            }
        };


        binding.tvTest1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectivityManager.requestNetwork(networkRequest, networkCallback);
            }
        });

6.2 suggestion建议连接

WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
        .setSsid("zg123")
        .setWpa2Passphrase("Aa123456")
        .setIsAppInteractionRequired(true)
        .setIsUserInteractionRequired(false)
        .build();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
ArrayList<WifiNetworkSuggestion> suggestionsList = new ArrayList<>();
suggestionsList.add(suggestion);
int status = wifiManager.addNetworkSuggestions(suggestionsList);
Log.d(TAG, status + "");
if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {

}
IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
            return;
        }
    }
};
registerReceiver(broadcastReceiver, intentFilter);

6.3 两者结合

private void connectWifi(String ssid, String pwd) {
    // andorid 10以上
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
        //step1-创建建议列表
        WifiNetworkSuggestion suggestion =
                new WifiNetworkSuggestion.Builder()
                        .setSsid(ssid)
                        .setWpa2Passphrase((pwd))
                        .setIsAppInteractionRequired(true)
                        .build();

        List<WifiNetworkSuggestion> suggestionsList = new ArrayList<>();
        suggestionsList.add(suggestion);
        WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int status = wifiManager.addNetworkSuggestions(suggestionsList);
        // step2-添加建议成功
        if (status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
            WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
                    .setSsid(ssid)
                    .setWpa2Passphrase(pwd)
                    .build();

            NetworkRequest request = new NetworkRequest.Builder()
                    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                    .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    .setNetworkSpecifier(wifiNetworkSpecifier)
                    .build();

            ConnectivityManager mConnectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
            ConnectivityManager.NetworkCallback mNetworkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(@NonNull Network network) {
                    super.onAvailable(network);
                }

                @Override
                public void onUnavailable() {
                    super.onUnavailable();
                }
            };
            // step3-连接wifi
            mConnectivityManager.requestNetwork(request, mNetworkCallback);
        } else {
        }
    }
}

6.4 注意

  1. 部分设备不支持P2P,会出现连接失败,连接上WiFi不能上网等问题
  2. 建议的方式连接,有时候压根不听建议,所以没啥用

7.注意

  1. API 28 之前可以使用WifiManager来切换
  2. API 29及以上就需要使用NetworkRequest的方式进行切换,会弹出一个新的页面(新界面或弹窗)

8.NFC 或 QR 码

Android 12 引入了 Easy Connect 功能,使得连接 WiFi 更加简单。通过 NFC 或 QR 码可以轻松连接到无线网络。下面是一个使用 NFC 连接 WiFi 的示例代码:

NdefMessage message = new NdefMessage(new NdefRecord[] {
    NdefRecord.createWifiConfig("MyWifi", "password", WifiConfiguration.KeyMgmt.WPA2_PSK)
});

NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);

nfcAdapter.setNdefPushMessage(message, this);

9.跳WiFi设置

Kotlin 复制代码
startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))

这个方式最稳。

10.参考

android 连接指定设备 wifi android自动连接指定wifi

Android WIFI连接总结

android12 wifi自动连接流程

Android 10+ Wifi连接(一)

Android10+ Wifi连接后Socket通信(二)

Android WIFI (一) 扫描WIFI

Android WIFI(二)连接WIFI

官网地址

android通过代码连接wifi

Android app应用连接WiFi的方法(兼容Android10)

相关推荐
SRC_BLUE_1728 分钟前
SQLI LABS | Less-39 GET-Stacked Query Injection-Intiger Based
android·网络安全·adb·less
无尽的大道4 小时前
Android打包流程图
android
镭封5 小时前
android studio 配置过程
android·ide·android studio
夜雨星辰4875 小时前
Android Studio 学习——整体框架和概念
android·学习·android studio
邹阿涛涛涛涛涛涛5 小时前
月之暗面招 Android 开发,大家快来投简历呀
android·人工智能·aigc
IAM四十二6 小时前
Jetpack Compose State 你用对了吗?
android·android jetpack·composer
奶茶喵喵叫6 小时前
Android开发中的隐藏控件技巧
android
Winston Wood8 小时前
Android中Activity启动的模式
android
众乐认证8 小时前
Android Auto 不再用于旧手机
android·google·智能手机·android auto
三杯温开水8 小时前
新的服务器Centos7.6 安卓基础的环境配置(新服务器可直接粘贴使用配置)
android·运维·服务器