示例#1
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    if (!WifiFeature.isWifiSupported(getContext())) {
      // skip the test if WiFi is not supported
      return;
    }
    mMySync = new MySync();
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    mIntentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);

    mContext.registerReceiver(mReceiver, mIntentFilter);
    mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
    assertNotNull(mWifiManager);
    mWifiLock = mWifiManager.createWifiLock(TAG);
    mWifiLock.acquire();
    if (!mWifiManager.isWifiEnabled()) setWifiEnabled(true);
    Thread.sleep(ENABLE_WAIT_MSEC);
    assertTrue(mWifiManager.isWifiEnabled());
    mMySync.expectedState = STATE_NULL;
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // If the user is not allowed to configure wifi, do not handle menu selections.
    if (mUserManager.hasUserRestriction(DISALLOW_CONFIG_WIFI)) return false;

    switch (item.getItemId()) {
      case MENU_ID_WPS_PBC:
        showDialog(WPS_PBC_DIALOG_ID);
        return true;
      case MENU_ID_P2P:
        if (getActivity() instanceof PreferenceActivity) {
          ((PreferenceActivity) getActivity())
              .startPreferencePanel(
                  WifiP2pSettings.class.getCanonicalName(),
                  null,
                  R.string.wifi_p2p_settings_title,
                  null,
                  this,
                  0);
        } else {
          startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null);
        }
        return true;
      case MENU_ID_WPS_PIN:
        showDialog(WPS_PIN_DIALOG_ID);
        return true;
      case MENU_ID_SCAN:
        if (mWifiManager.isWifiEnabled()) {
          mScanner.forceScan();
        }
        return true;
      case MENU_ID_ADD_NETWORK:
        if (mWifiManager.isWifiEnabled()) {
          onAddNetworkPressed();
        }
        return true;
      case MENU_ID_ADVANCED:
        if (getActivity() instanceof PreferenceActivity) {
          ((PreferenceActivity) getActivity())
              .startPreferencePanel(
                  AdvancedWifiSettings.class.getCanonicalName(),
                  null,
                  R.string.wifi_advanced_titlebar,
                  null,
                  this,
                  0);
        } else {
          startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
  private void updateConnectionState(DetailedState state) {
    /* sticky broadcasts can call this when wifi is disabled */
    if (!mWifiManager.isWifiEnabled()) {
      mScanner.pause();
      return;
    }

    if (state == DetailedState.OBTAINING_IPADDR) {
      mScanner.pause();
    } else {
      mScanner.resume();
    }

    mLastInfo = mWifiManager.getConnectionInfo();
    if (state != null) {
      mLastState = state;
    }

    for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) {
      // Maybe there's a WifiConfigPreference
      Preference preference = getPreferenceScreen().getPreference(i);
      if (preference instanceof AccessPoint) {
        final AccessPoint accessPoint = (AccessPoint) preference;
        accessPoint.update(mLastInfo, mLastState);
      }
    }
  }
  /** Refreshes acccess points and ask Wifi module to scan networks again. */
  /* package */ void refreshAccessPoints() {
    if (mWifiManager.isWifiEnabled()) {
      mScanner.resume();
    }

    getPreferenceScreen().removeAll();
  }
  /* package */ void submit(WifiConfigController configController) {

    final WifiConfiguration config = configController.getConfig();

    if (config == null) {
      if (mSelectedAccessPoint != null && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
        mWifiManager.connect(mSelectedAccessPoint.networkId, mConnectListener);
      }
    } else if (config.networkId != INVALID_NETWORK_ID) {
      if (mSelectedAccessPoint != null) {
        mWifiManager.save(config, mSaveListener);
      }
    } else {
      if (configController.isEdit()) {
        mWifiManager.save(config, mSaveListener);
      } else {
        mWifiManager.connect(config, mConnectListener);
      }
    }

    if (mWifiManager.isWifiEnabled()) {
      mScanner.resume();
    }
    updateAccessPoints();
  }
示例#6
0
  /** 打开WIFI */
  public void OpenWifi() {
    if (mWifiManager.isWifiEnabled()) {
      return;
    }

    mWifiManager.setWifiEnabled(true);
  }
  /**
   * Gathers WiFi signal measurements using the external native library.
   *
   * @param timeout in milli seconds when data gathering should be stopped if no data was provided
   *     by the operating system
   * @return access point data (or an empty array)
   */
  @Override
  public AccessPointData[] gatherWifiSignals(int timeout) {
    // TODO timeout wird aktuell nicht verwendet
    List<ScanResult> scanResults = null;

    if (context != null) {
      WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      // falls Wifi aktiviert
      if (wifiManager.isWifiEnabled()) {
        wifiManager.startScan();
        scanResults = wifiManager.getScanResults();
      }
    }

    if (scanResults != null) {
      int resultCount = scanResults.size();
      AccessPointData[] results = new AccessPointData[resultCount];
      for (ScanResult sr : scanResults) {
        results[resultCount - 1] =
            new AccessPointData(sr.BSSID, sr.level, -1, sr.frequency, -1, sr.SSID);
        resultCount--;
      }
      return results;
    } else {
      // falls Wifi deaktiviert
      // Log.d("WIFI_TEST", "Wifi ist deaktiviert! Wifi muss "
      //		+ "aktiviert werden um die AccessPoints zu scannnen!");
      return new AccessPointData[0]; // empty Array;
    }
  }
  private void checkWifiState() {
    // Enable WIFI.
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifi != null && !wifi.isWifiEnabled()) {
      AlertDialog alertDialog = new AlertDialog.Builder(this).create();
      alertDialog.setTitle("Exit");
      alertDialog.setMessage(
          "You need an internet connection to create an account. "
              + "Please enable a data connection and try again.");

      // Ok button.
      alertDialog.setButton(
          AlertDialog.BUTTON_POSITIVE,
          "Ok",
          new AlertDialog.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
              Intent intent = new Intent();
              intent.putExtra(MainActivity.EXTRA_REGISTERED, false);
              intent.putExtra(MainActivity.EXTRA_USER_ID, -1);
              setResult(Activity.RESULT_CANCELED, intent);
              finish();
            }
          });
      alertDialog.show();
    }
  }
示例#9
0
  @Override
  public Observable<Void> enableWifi() {
    return Observable.create(
        subscriber -> {
          Log.d("WifiService", "It has been requested to enable the Wifi.");
          boolean isWifiEnabled = wifiManager.isWifiEnabled();
          if (isWifiEnabled) {
            Log.d("WifiService", "The Wifi is already enabled.");
            subscriber.onCompleted();
          } else {
            wifiStateChangedSubscribers.add(subscriber);

            if (wifiStateChangedReceiver != null) {
              Log.d("WifiService", "Another request to enable the Wifi is in process.");
            } else {
              wifiStateChangedReceiver = new WifiStateChangedReceiver();
              getContext()
                  .registerReceiver(
                      wifiStateChangedReceiver,
                      new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
              Log.d(
                  "WifiService",
                  wifiStateChangedReceiver.getClass().getSimpleName() + " registered.");

              wifiManager.setWifiEnabled(true);
              Log.d("WifiService", "Enabling the Wifi...");
            }
          }
        });
  }
  private void setWifiStatus(boolean onOff) {
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (onOff) {
      if (wifi.isWifiEnabled() == false) {
        Toast.makeText(
                getApplicationContext(),
                "Wifi is disabled. It is being enabled.",
                Toast.LENGTH_LONG)
            .show();
      }
      wifi.setWifiEnabled(true);
      scanning_textView.setVisibility(View.GONE);
      wifiListview.setVisibility(View.VISIBLE);
      wifiOnOff.setChecked(true);
      wifiOnOff.setBackgroundColor(getResources().getColor(R.color.greenEnd));
    } else {

      Toast.makeText(getApplicationContext(), "Wifi is disabled.", Toast.LENGTH_LONG).show();
      wifi.setWifiEnabled(false);
      wifiOnOff.setChecked(false);
      wifiOnOff.setBackgroundColor(getResources().getColor(R.color.lightGrey));
      scanning_textView.setVisibility(View.GONE);
      wifiListview.setVisibility(View.GONE);
    }
  }
  private void initList() {
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifi.isWifiEnabled() == false) {
      Toast.makeText(
              getApplicationContext(), "Wifi is disabled. It is being enabled.", Toast.LENGTH_LONG)
          .show();
      wifi.setWifiEnabled(true);
    }

    setWifiStatus(true);
    wifi.startScan();

    try {
      size = size - 1;
      if (size > 0) {
        scanning_textView.setVisibility(View.GONE);
        wifiListview.setVisibility(View.VISIBLE);
        setWifiList();
      } else {
        scanning_textView.setVisibility(View.VISIBLE);
        wifiListview.setVisibility(View.GONE);
      }
      while (size >= 0) {
        size--;

        listAdapter.notifyDataSetChanged();
      }
    } catch (Exception e) {
    }
  }
 public boolean isWifiAvailable() {
   WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
   if (wifiManager != null && wifiManager.isWifiEnabled()) {
     return true;
   }
   return false;
 }
  public void updateTimer() {

    //
    // Check if the time since the last scan has been 60 secs
    // If Not just reset the time since last scan to 60 secs
    // else
    // Request a scan
    //
    try {
      currentTime = System.currentTimeMillis();
      long timeSinceLastScan = currentTime - lastScanTime;
      if (timeSinceLastScan >= 60000) {
        if (!wifiMgr.isWifiEnabled() || !wifiMgr.startScan()) {
          Log.v(TAG, "startScan() returned error");
          lastScanTime = System.currentTimeMillis();
        }
        tHandler.postDelayed(tUpdateTimerRunnable, 60000);
      } else {
        tHandler.postDelayed(tUpdateTimerRunnable, 60000 - timeSinceLastScan);
      }
    } catch (SecurityException se) {
      Log.e(
          TAG,
          "Possible missing permissions needed to run ICE over AllJoyn. Discovery over ICE in AllJoyn may not work due to this");
      se.printStackTrace();
    }
  }
 @Override
 protected void onStart() {
   super.onStart();
   if (!wifiManager.isWifiEnabled()) {
     onWifiDisabled();
   }
 }
示例#15
0
	/**
	 * Function: 打开wifi功能<br>
	 * 
	 * @author ZYT DateTime 2014-5-14 上午11:01:11<br>
	 * @return true:打开成功;false:打开失败<br>
	 */
	public boolean openWifi() {
		boolean bRet = true;
		if (!mWifiManager.isWifiEnabled()) {
			bRet = mWifiManager.setWifiEnabled(true);
		}
		return bRet;
	}
  @Override
  void initValues() {
    mContext = Add_DeviceActivity.this;
    mBackClassName = getBackClassName();
    mNowClassName = getNowClassName();

    mWifiManger = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> listWifiConfiguration = mWifiManger.getConfiguredNetworks();

    //        Log.e("mWifiManger.isWifiEnabled()", "wifiEnabled:" + mWifiManger.isWifiEnabled());
    if (!mWifiManger.isWifiEnabled()) {
      Toast.makeText(this, getString(R.string.open_wifi), Toast.LENGTH_SHORT).show();
      startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
      overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
    } else {
      for (int i = 0; i < listWifiConfiguration.size(); i++) {
        if (mWifiManger.getConnectionInfo().getSSID().equals(listWifiConfiguration.get(i).SSID)) {
          mOriginWifiConfig = listWifiConfiguration.get(i);
        }
      }
    }

    mWifiScanReceiver = new WifiScanReceiver();
    mWifiChangeReceiver = new WifiChangeReceiver();
  }
 /* package */ int getAccessPointsCount() {
   final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
   if (wifiIsEnabled) {
     return getPreferenceScreen().getPreferenceCount();
   } else {
     return 0;
   }
 }
示例#18
0
 /** 判断wifi是否开启 */
 private static boolean isWIFIEnabled(Context context) {
   boolean enable = false;
   WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
   if (wifiManager.isWifiEnabled()) {
     enable = true;
   }
   return enable;
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

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

    wlanSwitch = (Switch) rootView.findViewById(R.id.switch1);
    dataSwitch = (Switch) rootView.findViewById(R.id.switch2);

    if (wifiManager.isWifiEnabled()) wlanSwitch.setChecked(true);
    else wlanSwitch.setChecked(false);

    if (isMobileDataEnabled()) dataSwitch.setChecked(true);
    else dataSwitch.setChecked(false);

    wlanSwitch.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (wifiManager.isWifiEnabled()) {
              wifiManager.setWifiEnabled(false);
              wlanSwitch.setChecked(false);
            } else {
              wifiManager.setWifiEnabled(true);
              wlanSwitch.setChecked(true);
            }
          }
        });

    dataSwitch.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isMobileDataEnabled()) {
              try {
                setMobileDataEnabled(getActivity(), false);
              } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Error: Data is enabled", Toast.LENGTH_SHORT).show();
              }
              dataSwitch.setChecked(false);
            } else {
              try {
                setMobileDataEnabled(getActivity(), true);
              } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "ErrorError: Data is disabled", Toast.LENGTH_SHORT)
                    .show();
              }
              dataSwitch.setChecked(true);
            }
          }
        });

    return rootView;
  }
示例#20
0
  private void changeWifi() {
    WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr.isWifiEnabled()) {
      wifiMgr.setWifiEnabled(false);
    } else {
      wifiMgr.setWifiEnabled(true);
    }
  }
示例#21
0
 public final boolean c()
 {
     if (a == null || b == null)
     {
         return false;
     } else
     {
         return b.isWifiEnabled();
     }
 }
示例#22
0
  public static byte[] getLocalIpInt(Context context) {
    WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    if (!wm.isWifiEnabled()) {
      return null;
    }

    WifiInfo wi = wm.getConnectionInfo();
    return intToBytes(wi.getIpAddress());
  }
  /**
   * connecting to wifi with provided credentials
   *
   * @param ssid - network identificator
   * @param password - network password
   * @return flag indicating wifi connection state
   */
  private boolean connectToWifi(String ssid, String password) {

    final String TAG_WIFI_CONNECTING = "connectingToWiFi";
    WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

    if (!wifi.isWifiEnabled()) {
      if (!wifi.setWifiEnabled(true)) {
        Log.e("WiFi", "without WiFi won't work");
        return false;
      }
    }

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + ssid + "\"";
    conf.preSharedKey = "\"" + password + "\"";
    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);
    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    conf.status = WifiConfiguration.Status.ENABLED;
    int networkId = wifi.addNetwork(conf);
    wifi.disconnect();
    wifi.enableNetwork(networkId, true);
    boolean completed = wifi.reconnect();

    if (!completed) {
      Log.d(TAG_WIFI_CONNECTING, "repeat wifi connection attempt");
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      wifi.disconnect();
      wifi.enableNetwork(networkId, true);
      completed = wifi.reconnect();
    }

    /**
     * delay introduced in order to wait for establishing connection (flag from reconnect() is set
     * before network is really working)
     */
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    if (completed) {
      (new Setup(getApplicationContext())).start();
      logEvent(CONFIGURATION_TAG, "connected to Wi-Fi");
    }

    return completed;
  }
示例#24
0
文件: IpUtil.java 项目: stronglee/sdk
 public static String getWifiIp(Context context) {
   // 获取wifi服务
   WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
   // 判断wifi是否开启
   if (!wifiManager.isWifiEnabled()) {
     wifiManager.setWifiEnabled(true);
   }
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   return intToIp(ipAddress);
 }
 public static String getWifiIp(Context context) {
   WifiManager wifimanage =
       (WifiManager) context.getSystemService(Context.WIFI_SERVICE); // 获取WifiManager
   // 检查wifi是否开启
   if (!wifimanage.isWifiEnabled()) {
     wifimanage.setWifiEnabled(true);
   }
   WifiInfo wifiinfo = wifimanage.getConnectionInfo();
   String ip = intToIp(wifiinfo.getIpAddress());
   return ip;
 }
示例#26
0
 public static String getLocalIpAddress(Context context) {
   WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
   // 判断wifi是否开启
   if (!wifiManager.isWifiEnabled()) {
     wifiManager.setWifiEnabled(true);
   }
   // 使用wifi获得有问题,可能要真机测试
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   return intToIpAddress(ipAddress);
 }
示例#27
0
  private String getIp() {
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    // 检查Wifi状态
    if (!wm.isWifiEnabled()) return null;

    WifiInfo wi = wm.getConnectionInfo();
    // 获取32位整型IP地址
    int ipAdd = wi.getIpAddress();
    // 把整型地址转换成“*.*.*.*”地址
    return intToIp(ipAdd);
  }
示例#28
0
  /*
   * Returns empty ArrayList<WFScanResult> if wifi off or scan results null
   */
  private List<WFScanResult> getNetworks(Context context) {
    WifiManager wm = AsyncWifiManager.getWifiManager(context);

    if (wm.isWifiEnabled()) {
      List<WFScanResult> scanned = WFScanResult.fromScanResultArray(wm.getScanResults());
      if (scanned != null) {
        Collections.sort(scanned, new SortBySignal());
        return scanned;
      }
    }
    return new ArrayList<WFScanResult>();
  }
示例#29
0
  public static boolean isWiFiActive(Context context) {
    WifiManager wm = null;
    try {
      wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (wm == null || wm.isWifiEnabled() == false) return false;

    return true;
  }
示例#30
0
  @Override
  public void run() {

    try {
      while (true) {
        Log.d("graph", "foi");
        if (wifi.isWifiEnabled()) {
          WifiInfo wifiINFO = wifi.getConnectionInfo();
          Log.d("MyDebug", "" + wifiINFO.getIpAddress());
          wifi.startScan();
          List<ScanResult> sr = wifi.getScanResults();

          for (WifiStrengthXYSeries s : hash.values()) {
            plot.removeSeries(s);
          }
          plot.removeMarkers();

          for (ScanResult r : sr) {
            WifiStrengthXYSeries series = hash.get(r.SSID);
            if (series == null) {
              series =
                  new WifiStrengthXYSeries(
                      r.SSID,
                      (r.frequency - 2407) / 5,
                      r.level,
                      ColorPool.getColor(hash.size()),
                      ColorPool.getTransparentColor(hash.size()));
              hash.put(r.SSID, series);

            } else {
              series.setChannel((r.frequency - 2407) / 5);
              series.setStrength(r.level);
              series.update();
            }

            plot.addSeries(series, series.getFormatter());
            plot.addMarker(
                series.getMarker(activity.getResources().getConfiguration().orientation));
          }

          plot.redraw();
        }
        Thread.sleep(1000);
      }

    } catch (InterruptedException e) {

      for (WifiStrengthXYSeries s : hash.values()) {
        plot.removeSeries(s);
      }
    }
  }