首页 > 解决方案 > Api 级别 29 及以上的 Android 点对点 wifi 连接问题

问题描述

我在 API 级别 29 及更高级别面临 Android 点对点 WIFI 连接问题,它在 API 级别低于 29 时工作正常

这里我分享代码

public static Task<Boolean>  ConnectToWifi( String networkSSID, String password,Context context ){
        final TaskCompletionSource<Boolean> tcs = new TaskCompletionSource<>();
        try {

         WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes

        conf.preSharedKey = "\"" + password + "\"";

         conf.status = WifiConfiguration.Status.ENABLED;
         conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
         conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
         conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
         conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
         conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

         Log.d("connecting", conf.SSID + " " + conf.preSharedKey);

         WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
         wifiManager.addNetwork(conf);

         Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);



         List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
         for( WifiConfiguration i : list ) {
             if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                 wifiManager.disconnect();
                 wifiManager.enableNetwork(i.networkId, true);
                 wifiManager.reconnect();
                 Log.d("re connecting", i.SSID + " " + conf.preSharedKey);

                 break;
             }
         }


         //WiFi Connection success, return true
        tcs.setResult(true);
     } catch (Exception ex) {
         System.out.println(Arrays.toString(ex.getStackTrace()));
        Toast.makeText(context, Arrays.toString(ex.getStackTrace()), Toast.LENGTH_SHORT).show();
        tcs.setResult(false);
     }
    return tcs.getTask();
}

我已经搜索但找不到任何解决方案,请有人帮我解决问题。谢谢

标签: javaandroid

解决方案


推荐阅读