1

我正在实现一种方法,如果连接到 wifi 网络失败,它会尝试使用警报对话框重新连接,这是我到目前为止的代码

public boolean autoConnect() {
      String networkSSID = "xxxxx";
      boolean connected = false;
      WifiConfiguration conf = new WifiConfiguration();

      conf.SSID = "\"" + networkSSID + "\"";
      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
      WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
      wifiManager.addNetwork(conf);
      wifiManager.startScan();
      List<ScanResult> list = wifiManager.getScanResults();
      AlertDialog alertDialog = new AlertDialog.Builder(CarNannyv3Activity.this).create();
      alertDialog.setTitle("xxxxxxxx Not Available");  
      alertDialog.setMessage("Please make sure xxxxxx is turned on ");  
      alertDialog.setButton("Reconnect", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                autoConnect();
                dialog.dismiss();


            } });
      for( ScanResult i : list ) {
          if(i.SSID.equals("\"" + networkSSID + "\"")) {

               //wifiManager.enableNetwork(i.networkId, true);
               wifiManager.reconnect();               
               return connected = true;


          }else{

                alertDialog.show();
          }
       } 
      return connected;
  }

我得到两件事之一,它要么无限循环重新连接对话框,要么根本不显示,请告诉我我做错了什么。

4

1 回答 1

0

尝试使用它,它在我的情况下工作::

        WifiManager notif_manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        List<ScanResult> scan_list = notif_manager.getScanResults();
        for (ScanResult scan_ap : scan_list) 
        {
            if (scan_ap.SSID.equals("\"" + networkSSID + "\"")) 
            {

            /* Create a WifiConfig */
                WifiConfiguration eliteAp = new WifiConfiguration();

                /* AP Name */
                eliteAp.SSID = "\"" + ssidString + "\"";

                /* Priority */
                eliteAp.priority = 40;

                /* Enable Hidden SSID */
                eliteAp.hiddenSSID = false;
                .
                .
                .
                .
                .
                .       
                eliteAp.status = WifiConfiguration.Status.ENABLED;
                int res = wifi_manager.addNetwork(eliteAp);
                boolean d = wifi_manager.enableNetwork(res, true);
                break;

            }
        }
于 2012-12-20T07:32:45.930 回答