private void updateAccessPoints(List<ScanResult> scanResultList) {
    List<WifiAccessPoint> accessPoints = new ArrayList<WifiAccessPoint>();

    WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
    int ip = wifiInfo.getIpAddress();
    String ssid = wifiInfo.getSSID();

    List<ScanResult> results = scanResultList;
    if (results != null) {
      for (ScanResult result : results) {
        if (result.SSID == null
            || result.SSID.length() == 0
            || result.capabilities.contains("[IBSS]")) {
          continue;
        }
        boolean found = false;
        for (WifiAccessPoint accessPoint : accessPoints) {
          if (accessPoint.update(result)) {
            found = true;
          }
        }
        if (!found) {
          WifiAccessPoint accessPoint = new WifiAccessPoint(result);
          ssid = WifiUtil.removeDoubleQuotes(ssid);

          if (ssid != null && result.SSID.compareTo(ssid) == 0 && ip > 0) {
            accessPoint.setConnectStatus(WifiConst.CONNCETED);
          }
          accessPoints.add(accessPoint);
        }
      }
    }
    mAccessPoints = accessPoints;
  }
 private int isFreeHotspot(ScanResult result) {
   if (isOpenWLAN(result)) {
     if (result.SSID.toLowerCase(Locale.US).contains("freifunk"))
       return WMapEntry.FLAG_IS_FREIFUNK;
     if (result.SSID.toLowerCase(Locale.US).compareTo("mesh") == 0)
       return WMapEntry.FLAG_IS_FREIFUNK;
     if (result.SSID.toLowerCase(Locale.US).compareTo("free-hotspot.com") == 0)
       return WMapEntry.FLAG_IS_FREEHOTSPOT;
     if (result.SSID.toLowerCase(Locale.US).contains("the cloud"))
       return WMapEntry.FLAG_IS_THECLOUD;
     return WMapEntry.FLAG_IS_OPEN;
   }
   return 0;
 }
Пример #3
0
  /**
   * This method initiates the connect process
   *
   * @param config an array containing the SSID and the password of the network
   * @param context android context
   */
  public void connect(String[] config, Context context) {

    identificationMissing = false;
    wlanKeyMissing = false;

    wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    adhoc = new AdhocWifiManager(wifi);
    ssid = config[0];

    identification = preferences.getString("identification", "");

    if (identification.equals("")) {
      identificationMissing = true;
    }

    boolean connectedSuccessful = false;

    // check whether the network is already known, i.e. the password is
    // already stored in the device
    for (WifiConfiguration configuredNetwork : wifi.getConfiguredNetworks()) {
      if (configuredNetwork.SSID.equals("\"".concat(ssid).concat("\""))) {
        connectedSuccessful = true;
        networkId = configuredNetwork.networkId;
        break;
      }
    }

    if (!connectedSuccessful) {
      for (ScanResult result : wifi.getScanResults()) {
        if (result.SSID.equals(ssid)) {
          connectedSuccessful = true;

          if (result.capabilities.contains("WPA") || result.capabilities.contains("WEP")) {
            wlanKeyMissing = true;
          }
          break;
        }
      }
    }

    if (connectedSuccessful) {

      if (identificationMissing || wlanKeyMissing) {
        identificationWlanKeyDialogFragment =
            new IdentificationWlanKeyDialogFragment(identificationMissing, wlanKeyMissing);
        identificationWlanKeyDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.Dialog);
        identificationWlanKeyDialogFragment.show(
            getFragmentManager(), "identificationWlanKeyDialogFragment");
      } else {
        adhoc.connectToNetwork(networkId, this);
      }
    } else {
      for (int i = 0; i < 2; i++)
        Toast.makeText(
                this, getString(R.string.toast_network_not_found_text, ssid), Toast.LENGTH_SHORT)
            .show();
    }
  }
 public int getCurrentChannel() {
   List<ScanResult> scanResults = wifiManager.getScanResults();
   for (ScanResult result : scanResults) {
     if (result.BSSID.equalsIgnoreCase(wifiInfo.getBSSID())
         && result.SSID.equalsIgnoreCase(currentSSID.substring(1, currentSSID.length() - 1))) {
       return getChannelByFrequency(result.frequency);
     }
   }
   return -1;
 }
  /** Returns sorted list of access points */
  private List<AccessPoint> constructAccessPoints() {
    ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
    /**
     * Lookup table to more quickly update AccessPoints by only considering objects with the correct
     * SSID. Maps SSID -> List of AccessPoints with the given SSID.
     */
    Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>();

    final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
    if (configs != null) {
      for (WifiConfiguration config : configs) {
        AccessPoint accessPoint = new AccessPoint(getActivity(), config);
        accessPoint.update(mLastInfo, mLastState);
        accessPoints.add(accessPoint);
        apMap.put(accessPoint.ssid, accessPoint);
      }
    }

    final List<ScanResult> results = mWifiManager.getScanResults();
    if (results != null) {
      for (ScanResult result : results) {
        // Ignore hidden networks.
        if (result.SSID == null || result.SSID.length() == 0) {
          continue;
        }

        // Ignore IBSS if chipset does not support them
        if (!mIbssSupported && result.capabilities.contains("[IBSS]")) {
          continue;
        }

        boolean found = false;
        for (AccessPoint accessPoint : apMap.getAll(result.SSID)) {
          if (accessPoint.update(result)) found = true;
        }
        if (!found) {
          AccessPoint accessPoint = new AccessPoint(getActivity(), result);
          accessPoints.add(accessPoint);
          apMap.put(accessPoint.ssid, accessPoint);
        }
      }
    }

    // Pre-sort accessPoints to speed preference insertion
    Collections.sort(accessPoints);
    return accessPoints;
  }
Пример #6
0
    @Override
    public void onReceive(Context c, Intent intent) {
      List<ScanResult> results = nm.wifi.getScanResults();
      ScanResult bestSignal = null;

      if (nm.state == State.SCANNING) {
        Log.i("starwisp", "Scanning " + nm.state);

        for (ScanResult result : results) {
          if (result.SSID.equals(SSID)) {
            Log.i("starwisp", "scan result for..." + SSID);
            m_Builder.DialogCallback(m_Context, m_Context.m_Name, m_CallbackName, "\"In range\"");
            nm.Connect();
            return;
          }
        }

        if (nm.state == State.SCANNING) {
          Log.i("starwisp", "REScanning " + nm.state);
          nm.wifi.startScan();
        }
      }
    }
  public void connectToAP(String ssid, String passkey, Context ctx) {
    //	    Log.i(TAG, "* connectToAP");

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
    String networkSSID = ssid;
    String networkPass = passkey;

    //	    Log.d(TAG, "# password " + networkPass);
    if (results != null && results.size() > 0) {
      for (ScanResult result : results) {
        if (result.SSID.equals(networkSSID)) {

          String securityMode = getScanResultSecurity(result);

          if (securityMode.equalsIgnoreCase("OPEN")) {

            wifiConfiguration.SSID = "\"" + networkSSID + "\"";
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            int res = wifiManager.addNetwork(wifiConfiguration);
            //	                Log.d(TAG, "# add Network returned " + res);

            wifiManager.enableNetwork(res, true);
            //	                Log.d(TAG, "# enableNetwork returned " + b);

            wifiManager.setWifiEnabled(true);

          } else if (securityMode.equalsIgnoreCase("WEP")) {

            wifiConfiguration.SSID = "\"" + networkSSID + "\"";
            wifiConfiguration.wepKeys[0] = "\"" + networkPass + "\"";
            wifiConfiguration.wepTxKeyIndex = 0;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            int res = wifiManager.addNetwork(wifiConfiguration);
            //	                Log.d(TAG, "### 1 ### add Network returned " + res);

            wifiManager.enableNetwork(res, true);
            //	                Log.d(TAG, "# enableNetwork returned " + b);

            wifiManager.setWifiEnabled(true);
          }

          wifiConfiguration.SSID = "\"" + networkSSID + "\"";
          wifiConfiguration.preSharedKey = "\"" + networkPass + "\"";
          wifiConfiguration.hiddenSSID = true;
          wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
          wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
          wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
          wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
          wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
          wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
          wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
          wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

          int res = wifiManager.addNetwork(wifiConfiguration);

          wifiManager.enableNetwork(res, true);

          boolean changeHappen = wifiManager.saveConfiguration();

          wifiManager.setWifiEnabled(true);
          if (res != -1 && changeHappen) {

            if (!checkNetwrk())
              Toast.makeText(
                      ctx,
                      "wifi password is set but no internet access. Restart the router",
                      Toast.LENGTH_LONG)
                  .show();
            else Toast.makeText(ctx, "wifi is connected", Toast.LENGTH_LONG).show();
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            Intent i = new Intent(ctx, InternetConnectionSetting.class);
            startActivity(i);
            finish();
          }
        }
      }
    } else {
      getWifiList();
    }
  }
  public void run() {
    int i,
        j,
        storedValues,
        sleepTime = 3000,
        timeoutCtr = 0,
        lastFlags = -1,
        trackCnt = 0,
        lastLocMethod = -5;
    String bssid;
    WMapEntry currEntry;
    DataOutputStream out;
    FileInputStream in;

    while (running) {
      try {
        if (scanData.getNoGPSExitInterval() > 0) {
          if (System.currentTimeMillis() > lastGPSTime + scanData.getNoGPSExitInterval()) {
            break;
          }
        }
        if (ScanService.scanData.getThreadMode() == OWMapAtAndroid.THREAD_MODE_UPLOAD) {
          if ((m_uploadThread != null) && (m_uploadThread.isUploading()))
            OWMapAtAndroid.sendMessage(
                ScannerHandler.MSG_SIMPLE_ALERT,
                0,
                0,
                getResources().getText(R.string.upload_in_progress));
          else m_uploadThread = new UploadThread(scanData, this, SP, false, notification, null);
          ScanService.scanData.setThreadMode(OWMapAtAndroid.THREAD_MODE_SCAN);
        } else {
          if ((posState == 0) && (scanData != null) && (scanData.isScanningEnabled())) {
            posState = 1;
            timeoutCtr = 0;
            if (scanData.getFlags() != lastFlags) {
              if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0)
                scanData.getWifiManager().createWifiLock(WifiManager.WIFI_MODE_FULL, "OpenWLANMap");
              else
                scanData
                    .getWifiManager()
                    .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "OpenWLANMap");
              lastFlags = scanData.getFlags();
            }
            if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0)
              myWLocate.wloc_request_position(WLocate.FLAG_NO_IP_LOCATION);
            else {
              myWLocate.wloc_request_position(
                  WLocate.FLAG_NO_NET_ACCESS | WLocate.FLAG_NO_IP_LOCATION);
              //                  stopGoogleLocation();
            }
          } else if (!scanData.isScanningEnabled()) {
            try {
              trackCnt += 1500;
              Thread.sleep(1500);
            } catch (InterruptedException ie) {

            }
          }
          if (posState == 1) {
            // sleep while waiting for result
            try {
              trackCnt += 2500;
              java.lang.Thread.sleep(2500); // is interrupted from result handler
              timeoutCtr++;
              if (timeoutCtr > 3) {
                timeoutCtr = 0;
                posState = 0;
              }
            } catch (InterruptedException ie) {
            }
          }
          if ((posState == 2) || (posState == 100)) {
            loc_info locationInfo;
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            locationInfo = myWLocate.last_location_info();
            if (lastLocMethod != locationInfo.lastLocMethod) {
              scanData.getmView().setMode(locationInfo.lastLocMethod);
              scanData.getmView().postInvalidate();
              lastLocMethod = locationInfo.lastLocMethod;
            }
            if (posState == 100) locationInfo.lastLocMethod = -1;
            OWMapAtAndroid.sendMessage(
                OWMapAtAndroid.ScannerHandler.MSG_UPD_LOC_STATE,
                (int) (lastRadius * 1000),
                locationInfo.lastLocMethod,
                locationInfo);

            if (SP.getBoolean("autoConnect", false)) {
              if (!mWifi.isConnected()) {
                for (i = 0; i < locationInfo.wifiScanResult.size(); i++) {
                  ScanResult result;

                  result = locationInfo.wifiScanResult.get(i);
                  result.capabilities = result.capabilities.toUpperCase(Locale.US);
                  if ((isFreeHotspot(result) & WMapEntry.FLAG_IS_FREIFUNK) != 0) {
                    // auto-connect to this open network

                    WifiConfiguration wifiConfig = new WifiConfiguration();
                    wifiConfig.BSSID = result.BSSID;
                    wifiConfig.priority = 1;
                    wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
                    wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    wifiConfig.status = WifiConfiguration.Status.ENABLED;

                    int netId = scanData.getWifiManager().addNetwork(wifiConfig);
                    scanData.getWifiManager().enableNetwork(netId, true);
                  }
                }
              }
            }
            if ((posValid)
                && (locationInfo.wifiScanResult != null)
                && (locationInfo.wifiScanResult.size() > 0)) {
              boolean foundExisting;

              for (i = 0; i < locationInfo.wifiScanResult.size(); i++) {
                ScanResult result;

                result = locationInfo.wifiScanResult.get(i);
                bssid = result.BSSID.replace(":", "").replace(".", "").toUpperCase(Locale.US);
                if (bssid.equalsIgnoreCase("000000000000")) break;
                foundExisting = false;
                scanData.getLock().lock();
                for (j = 0; j < scanData.getWmapList().size(); j++) {
                  currEntry = scanData.getWmapList().elementAt(j);
                  if (currEntry.getBSSID().equalsIgnoreCase(bssid)) {
                    currEntry.setPos(lastLat, lastLon);
                    foundExisting = true;
                    break;
                  }
                }
                if (!foundExisting) {
                  String lowerSSID;

                  storedValues = scanData.incStoredValues();
                  scanData.getmView().setValue(storedValues);
                  scanData.getmView().postInvalidate();
                  currEntry = new WMapEntry(bssid, result.SSID, lastLat, lastLon, storedValues);
                  lowerSSID = result.SSID.toLowerCase(Locale.US);
                  if ((lowerSSID.endsWith("_nomap"))
                      || // Google unsubscibe option
                      (lowerSSID.contains("iphone"))
                      || // mobile AP
                      (lowerSSID.contains("android"))
                      || // mobile AP
                      (lowerSSID.contains("motorola"))
                      || // mobile AP
                      (lowerSSID.contains("deinbus.de"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("fernbus"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("flixbus"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("ecolines"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("eurolines_wifi"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("contiki-wifi"))
                      || // WLAN network on board of bus
                      (lowerSSID.contains("guest@ms "))
                      || // WLAN network on Hurtigruten ships
                      (lowerSSID.contains("admin@ms "))
                      || // WLAN network on Hurtigruten ships
                      (lowerSSID.contains("nsb_interakti"))
                      || // WLAN network in NSB trains
                      (lowerSSID.equals("southwestwifi"))) // WLAN network on Southwest flights
                  currEntry.setFlags(currEntry.getFlags() | WMapEntry.FLAG_IS_NOMAP);
                  else currEntry.setFlags(currEntry.getFlags() | isFreeHotspot(result));
                  if (isFreeHotspot(currEntry.getFlags())) scanData.incFreeHotspotWLANs();
                  scanData.getWmapList().add(currEntry);
                  if ((scanData.getUploadThres() > 0)
                      && (storedValues > scanData.getUploadThres())) {
                    if ((m_uploadThread == null) || (!m_uploadThread.isUploading())) {
                      if (mWifi.isConnected()) {
                        m_uploadThread =
                            new UploadThread(scanData, this, SP, true, notification, mWifi);
                      }
                    }
                  }
                }
                result.capabilities = result.capabilities.toUpperCase(Locale.US);
                scanData.getLock().unlock();
              }
            }
            scanData.getLock().lock();
            for (j = 0; j < scanData.getWmapList().size(); j++) {
              currEntry = scanData.getWmapList().elementAt(j);
              if ((currEntry.getLastUpdate() + OWMapAtAndroid.RECV_TIMEOUT
                      < System.currentTimeMillis())
                  && ((currEntry.getFlags() & WMapEntry.FLAG_IS_VISIBLE) == 0)) {
                scanData.getWmapList().remove(j);
                if (currEntry.posIsValid()) {
                  int padBytes = 0, k;

                  try {
                    in = scanData.getCtx().openFileInput(OWMapAtAndroid.WSCAN_FILE);
                    padBytes = in.available() % 28;
                    in.close();
                    if (padBytes > 0) padBytes = 28 - padBytes;
                  } catch (IOException ioe) {
                    ioe.printStackTrace();
                  }
                  try {
                    out =
                        new DataOutputStream(
                            scanData
                                .getCtx()
                                .openFileOutput(
                                    OWMapAtAndroid.WSCAN_FILE,
                                    Context.MODE_PRIVATE | Context.MODE_APPEND));
                    if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0);
                    out.write(currEntry.getBSSID().getBytes(), 0, 12);
                    if ((currEntry.getFlags() & WMapEntry.FLAG_IS_NOMAP) != 0) {
                      out.writeDouble(0.0);
                      out.writeDouble(0.0);
                    } else {
                      out.writeDouble(currEntry.getLat());
                      out.writeDouble(currEntry.getLon());
                    }
                    out.close();
                  } catch (IOException ioe) {
                    ioe.printStackTrace();
                  }

                  if ((currEntry.getFlags()
                          & (WMapEntry.FLAG_IS_FREIFUNK | WMapEntry.FLAG_IS_NOMAP))
                      == WMapEntry.FLAG_IS_FREIFUNK) {
                    padBytes = 0;
                    try {
                      in = scanData.getCtx().openFileInput(OWMapAtAndroid.WFREI_FILE);
                      padBytes = in.available() % 12;
                      in.close();
                      if (padBytes > 0) padBytes = 12 - padBytes;
                    } catch (IOException ioe) {
                      ioe.printStackTrace();
                    }
                    try {
                      out =
                          new DataOutputStream(
                              scanData
                                  .getCtx()
                                  .openFileOutput(
                                      OWMapAtAndroid.WFREI_FILE,
                                      Context.MODE_PRIVATE | Context.MODE_APPEND));
                      if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0);
                      out.write(currEntry.getBSSID().getBytes(), 0, 12);
                      out.close();
                    } catch (IOException ioe) {
                      ioe.printStackTrace();
                    }
                  }
                }
              }
              //               flushData(false);
            }
            scanData.getLock().unlock();
            m_lastSpeed = locationInfo.lastSpeed;
            if (!SP.getBoolean("adaptiveScanning", true)) sleepTime = 500;
            else if (locationInfo.lastSpeed > 90) sleepTime = 350;
            else if (locationInfo.lastSpeed < 0)
              sleepTime = 1300; // no speed information, may be because of WLAN localisation
            else if (locationInfo.lastSpeed < 6) sleepTime = 2500; // user seems to walk
            else {
              double f;

              f = 1.0 - (locationInfo.lastSpeed / 90.0);
              sleepTime = (int) ((1000.0 * f) + 350);
            }

            try {
              trackCnt += sleepTime;
              java.lang.Thread.sleep(sleepTime); // sleep between scans
            } catch (InterruptedException ie) {

            }
            posState = 0;
          }
        }
      } catch (NullPointerException npe) // in case the parent activity dies too fast
      {
        npe.printStackTrace();
      }
      if ((trackCnt > 500000) && (lastLat != 0) && (lastLon != 0)) {
        if (SP.getBoolean("track", false)) new UploadPositionTask().execute(null, null, null);
        trackCnt = 0;
      }
    }
    onDestroy(); // remove all resources (in case the thread was stopped due to some other reason
  }