简体   繁体   English

以编程方式将 android 设备连接到 wifi

[英]Connect android device to wifi programmatically

I need to connect my tablet to a wifi programmaticaly.我需要以编程方式将我的平板电脑连接到 wifi。 I have tried a least 20 differents codes, nothing works.我已经尝试了至少 20 种不同的代码,但没有任何效果。

I have all the permissions:我拥有所有权限:

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">

And here is the code:这是代码:

  WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", "ssis");
    wifiConfig.preSharedKey = String.format("\"%s\"", "password");


    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

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

    int netId = wifiManager.addNetwork(wifiConfig);
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();

The wifi protocol I use is WPA/WPA2我使用的wifi协议是WPA/WPA2

Does soemone has a working code? soemone 有工作代码吗?

Try this code this will work on all device except android 10. Check this https://issuetracker.google.com/issues/128554616试试这个代码,这将适用于除 android 10 以外的所有设备。检查这个https://issuetracker.google.com/issues/128554616

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", networkSSID);
wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);
wifiManager = (WifiManager)                         
getActivity().getApplicationContext().getSystemService(WIFI_SERVICE);
if(!wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM