Example #1
0
 /**
  * http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
  * http://developer.android.com/training/basics/network-ops/managing.html
  *
  * @param context
  * @return
  */
 public static boolean isNetworkAvailable(final Context context, final boolean mobile) {
   boolean available = false;
   try {
     final ConnectivityManager connectivitymanager =
         (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
     final NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
     if ((networkinfo != null) && networkinfo.isConnectedOrConnecting()) {
       switch (networkinfo.getType()) {
         case ConnectivityManager.TYPE_WIFI:
         case ConnectivityManager.TYPE_WIMAX:
         case ConnectivityManager.TYPE_ETHERNET:
           available = true;
           break;
         case ConnectivityManager.TYPE_MOBILE:
           if (mobile) {
             available = true;
           }
           break;
       }
     }
   } catch (Throwable x) {
     DBG.m(x);
   }
   return available;
 }
 /**
  * Record the roaming status of the device, and if it is a change from the previous status, send a
  * notification to any listeners.
  *
  * @param isRoaming {@code true} if the device is now roaming, {@code false} if it is no longer
  *     roaming.
  */
 protected void setRoamingStatus(boolean isRoaming) {
   if (isRoaming != mNetworkInfo.isRoaming()) {
     mNetworkInfo.setRoaming(isRoaming);
     Message msg = mTarget.obtainMessage(EVENT_ROAMING_CHANGED, mNetworkInfo);
     msg.sendToTarget();
   }
 }
  public NetworkInfo getNetworkInfo() {
    if (FeatureOption.MTK_GEMINI_SUPPORT) {
      getPhoneService(true);
      /*
       * If the phone process has crashed in the past, we'll get a
       * RemoteException and need to re-reference the service.
       */
      for (int retry = 0; retry < 2; retry++) {
        if (mPhoneService == null) {
          loge("Ignoring feature request because could not acquire PhoneService");
          break;
        }

        try {
          /**
           * M: update availabe info due to it may not correct when we received from
           * ACTION_ANY_DATA_CONNECTION_STATE_CHANGED
           */
          mNetworkInfo.setIsAvailable(mPhoneService.isDataConnectivityPossible());
          log("getNetworkInfo: updated IsAvailable=" + mNetworkInfo.isAvailable());
        } catch (RemoteException e) {
          if (retry == 0) getPhoneService(true);
        }
      }
    }

    return mNetworkInfo;
  }
  /**
   * Re-enable mobile data connectivity after a {@link #teardown()}.
   *
   * @param radioNum 0:sim1, 1:sim2
   */
  public boolean reconnectGemini(int radioNum) {
    boolean retValue = false; // false: failed, true: network is connecting or connected

    // reset teardown flag
    setTeardownRequested(false);
    switch (setEnableApnGemini(mApnType, true, radioNum)) {
      case PhoneConstants.APN_ALREADY_ACTIVE:
        // need to set self to CONNECTING so the below message is handled.
        // TODO: need to notify the app
        retValue = true;
        break;
      case PhoneConstants.APN_REQUEST_STARTED:
        // set IDLE here , avoid the following second FAILED not sent out
        if (!mNetworkInfo.isConnectedOrConnecting()) {
          mNetworkInfo.setDetailedState(DetailedState.IDLE, null, null);
        }
        retValue = true;
        break;
      case PhoneConstants.APN_REQUEST_FAILED:
      case PhoneConstants.APN_TYPE_NOT_AVAILABLE:
        break;
      default:
        loge("Error in reconnect - unexpected response.");
        break;
    }
    return retValue;
  }
 protected void setSubtype(int subtype, String subtypeName) {
   if (mNetworkInfo.isConnected()) {
     int oldSubtype = mNetworkInfo.getSubtype();
     if (subtype != oldSubtype) {
       mNetworkInfo.setSubtype(subtype, subtypeName);
       Message msg =
           mTarget.obtainMessage(EVENT_NETWORK_SUBTYPE_CHANGED, oldSubtype, 0, mNetworkInfo);
       msg.sendToTarget();
     }
   }
 }
Example #6
0
  public static boolean netIsAvailable(Context context) {
    NetworkInfo netInfo;
    ConnectivityManager connMgr =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    netInfo = connMgr.getActiveNetworkInfo();

    if (netInfo == null) {
      return false;
    }

    return netInfo.isConnected();
  }
  @RequestMapping(
      value = "/network",
      produces = {MediaType.APPLICATION_JSON_VALUE})
  public NetworkInfo checkNetworkAccess(
      @RequestParam(value = "targetIp") String pingIp,
      @RequestParam(value = "targetUrl") String pingUrl) {
    LOGGER.info("pingIp: {} - pingUrl: {}", pingIp, pingUrl);
    NetworkInfo networkInfo =
        new NetworkInfoBuilder().setPingIp(pingIp).setUrlPing(pingUrl).build();

    return networkInfo.status();
  }
  private EthernetDataTracker() {
    mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_ETHERNET, 0, NETWORKTYPE, "");
    mLinkProperties = new LinkProperties();
    mLinkCapabilities = new LinkCapabilities();
    mLinkUp = false;

    mNetworkInfo.setIsAvailable(false);
    setTeardownRequested(false);
  }
  private void interfaceRemoved(String iface) {
    if (!iface.equals(mIface)) return;

    Log.d(TAG, "Removing " + iface);

    NetworkUtils.stopDhcp(mIface);

    mLinkProperties.clear();
    mNetworkInfo.setIsAvailable(false);
    mNetworkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);

    Message msg = mCsHandler.obtainMessage(EVENT_CONFIGURATION_CHANGED, mNetworkInfo);
    msg.sendToTarget();

    msg = mCsHandler.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
    msg.sendToTarget();

    mIface = "";
  }
 /**
  * Record the detailed state of a network, and if it is a change from the previous state, send a
  * notification to any listeners.
  *
  * @param state the new @{code DetailedState}
  * @param reason a {@code String} indicating a reason for the state change, if one was supplied.
  *     May be {@code null}.
  * @param extraInfo optional {@code String} providing extra information about the state change
  */
 private void setDetailedState(NetworkInfo.DetailedState state, String reason, String extraInfo) {
   if (DBG)
     log("setDetailed state, old =" + mNetworkInfo.getDetailedState() + " and new state=" + state);
   if (state != mNetworkInfo.getDetailedState()) {
     boolean wasConnecting = (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING);
     String lastReason = mNetworkInfo.getReason();
     /*
      * If a reason was supplied when the CONNECTING state was entered, and no
      * reason was supplied for entering the CONNECTED state, then retain the
      * reason that was supplied when going to CONNECTING.
      */
     if (wasConnecting
         && state == NetworkInfo.DetailedState.CONNECTED
         && reason == null
         && lastReason != null) reason = lastReason;
     mNetworkInfo.setDetailedState(state, reason, extraInfo);
     Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, new NetworkInfo(mNetworkInfo));
     msg.sendToTarget();
   }
 }
 public void removeDefaultRoute() {
   if (mInterfaceName != null && mDefaultRouteSet == true) {
     if (DBG) {
       Log.d(
           TAG,
           "removeDefaultRoute for " + mNetworkInfo.getTypeName() + " (" + mInterfaceName + ")");
     }
     NetworkUtils.removeDefaultRoute(mInterfaceName);
     mDefaultRouteSet = false;
   }
 }
 /**
  * Record the detailed state of a network, and if it is a change from the previous state, send a
  * notification to any listeners.
  *
  * @param state the new @{code DetailedState}
  * @param reason a {@code String} indicating a reason for the state change, if one was supplied.
  *     May be {@code null}.
  * @param extraInfo optional {@code String} providing extra information about the state change
  * @param simId 0 for sim1 and 1 for sim2
  */
 public void setDetailedStateGemini(
     NetworkInfo.DetailedState state, String reason, String extraInfo, int simId) {
   if (DBG)
     log(
         "setDetailed state, old ="
             + mNetworkInfo.getDetailedState()
             + " and new state="
             + state
             + " simId is "
             + simId);
   if (state != mNetworkInfo.getDetailedState()) {
     boolean wasConnecting = (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING);
     String lastReason = mNetworkInfo.getReason();
     /*
      * If a reason was supplied when the CONNECTING state was entered, and no
      * reason was supplied for entering the CONNECTED state, then retain the
      * reason that was supplied when going to CONNECTING.
      */
     if (wasConnecting
         && state == NetworkInfo.DetailedState.CONNECTED
         && reason == null
         && lastReason != null) reason = lastReason;
     mNetworkInfo.setDetailedStateGemini(state, reason, extraInfo, simId);
     Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
     msg.sendToTarget();
   } else if (reason != null
       && (reason.equals(PhoneConstants.REASON_NO_SUCH_PDP)
           || reason.equals(Phone.REASON_APN_FAILED))
       && state == DetailedState.DISCONNECTED) {
     mNetworkInfo.setDetailedStateGemini(state, reason, extraInfo, simId);
     Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
     msg.sendToTarget();
   }
 }
  private void interfaceAdded(String iface) {
    if (!iface.matches(sIfaceMatch)) return;

    Log.d(TAG, "Adding " + iface);

    synchronized (mIface) {
      if (!mIface.isEmpty()) return;
      mIface = iface;
    }

    mNetworkInfo.setIsAvailable(true);
    Message msg = mCsHandler.obtainMessage(EVENT_CONFIGURATION_CHANGED, mNetworkInfo);
    msg.sendToTarget();

    runDhcp();
  }
 public void addDefaultRoute() {
   if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) {
     if (DBG) {
       Log.d(
           TAG,
           "addDefaultRoute for "
               + mNetworkInfo.getTypeName()
               + " ("
               + mInterfaceName
               + "), GatewayAddr="
               + mDefaultGatewayAddr);
     }
     NetworkUtils.setDefaultRoute(mInterfaceName, mDefaultGatewayAddr);
     mDefaultRouteSet = true;
   }
 }
 public void removePrivateDnsRoutes() {
   // TODO - we should do this explicitly but the NetUtils api doesnt
   // support this yet - must remove all.  No worse than before
   if (mInterfaceName != null && mPrivateDnsRouteSet) {
     if (DBG) {
       Log.d(
           TAG,
           "removePrivateDnsRoutes for "
               + mNetworkInfo.getTypeName()
               + " ("
               + mInterfaceName
               + ")");
     }
     NetworkUtils.removeHostRoutes(mInterfaceName);
     mPrivateDnsRouteSet = false;
   }
 }
 /**
  * Re-enable mobile data connectivity after a {@link #teardown()}. TODO - make async and always
  * get a notification?
  */
 public boolean reconnect() {
   boolean retValue = false; // connected or expect to be?
   setTeardownRequested(false);
   switch (setEnableApn(mApnType, true)) {
     case Phone.APN_ALREADY_ACTIVE:
       // need to set self to CONNECTING so the below message is handled.
       retValue = true;
       break;
     case Phone.APN_REQUEST_STARTED:
       // set IDLE here , avoid the following second FAILED not sent out
       mNetworkInfo.setDetailedState(DetailedState.IDLE, null, null);
       retValue = true;
       break;
     case Phone.APN_REQUEST_FAILED:
     case Phone.APN_TYPE_NOT_AVAILABLE:
       break;
     default:
       loge("Error in reconnect - unexpected response.");
       break;
   }
   return retValue;
 }
  /** Return the system properties name associated with the tcp buffer sizes for this network. */
  public String getTcpBufferSizesPropName() {
    int netType;
    String networkTypeStr = "unknown";
    TelephonyManager tm = new TelephonyManager(mContext);
    // TODO We have to edit the parameter for getNetworkType regarding CDMA
    if (FeatureOption.MTK_GEMINI_SUPPORT != true) {
      netType = tm.getNetworkType();
    } else {
      netType = tm.getNetworkTypeGemini(mNetworkInfo.getSimId());
    }

    // TODO We have to edit the parameter for getNetworkType regarding CDMA
    switch (netType) {
      case TelephonyManager.NETWORK_TYPE_GPRS:
        networkTypeStr = "gprs";
        break;
      case TelephonyManager.NETWORK_TYPE_EDGE:
        networkTypeStr = "edge";
        break;
      case TelephonyManager.NETWORK_TYPE_UMTS:
        networkTypeStr = "umts";
        break;
      case TelephonyManager.NETWORK_TYPE_HSDPA:
        networkTypeStr = "hsdpa";
        break;
      case TelephonyManager.NETWORK_TYPE_HSUPA:
        networkTypeStr = "hsupa";
        break;
      case TelephonyManager.NETWORK_TYPE_HSPA:
        networkTypeStr = "hspa";
        break;
      case TelephonyManager.NETWORK_TYPE_HSPAP:
        networkTypeStr = "hspap";
        break;
      case TelephonyManager.NETWORK_TYPE_CDMA:
        networkTypeStr = "cdma";
        break;
      case TelephonyManager.NETWORK_TYPE_1xRTT:
        networkTypeStr = "1xrtt";
        break;
      case TelephonyManager.NETWORK_TYPE_EVDO_0:
        networkTypeStr = "evdo";
        break;
      case TelephonyManager.NETWORK_TYPE_EVDO_A:
        networkTypeStr = "evdo";
        break;
      case TelephonyManager.NETWORK_TYPE_EVDO_B:
        networkTypeStr = "evdo";
        break;
      case TelephonyManager.NETWORK_TYPE_IDEN:
        networkTypeStr = "iden";
        break;
      case TelephonyManager.NETWORK_TYPE_LTE:
        networkTypeStr = "lte";
        break;
      case TelephonyManager.NETWORK_TYPE_EHRPD:
        networkTypeStr = "ehrpd";
        break;
      default:
        loge("unknown network type: " + tm.getNetworkType());
    }
    return "net.tcp.buffersize." + networkTypeStr;
  }
 /** Report whether data connectivity is possible. */
 public boolean isAvailable() {
   return mNetworkInfo.isAvailable();
 }
  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
  }
 /** @return true - If are we currently tethered with another device. */
 public synchronized boolean isAvailable() {
   return mNetworkInfo.isAvailable();
 }
@RunWith(Enclosed.class)
public class NemesisBlockMainnetTest {
  private static final NetworkInfo NETWORK_INFO = NetworkInfos.getMainNetworkInfo();
  private static final NemesisBlockInfo NEMESIS_BLOCK_INFO = NETWORK_INFO.getNemesisBlockInfo();
  // users, devs, marketing, contributors + funds (transfer + multisig)
  private static final int NUM_NEMESIS_TRANSFER_TRANSACTIONS = 1307 + 21 + 5 + 8 + 6;
  private static final int NUM_NEMESIS_TRANSACTIONS = NUM_NEMESIS_TRANSFER_TRANSACTIONS + 6;
  private static final Amount EXPECTED_MULTISIG_AGGREGATE_FEE =
      Amount.fromNem(2 * (5 + 3 * 4) + 2 * (5 + 3 * 5) + 2 * (5 + 3 * 6));
  private static final int EXPECTED_VERSION = 0x68000001;

  @BeforeClass
  public static void initNetwork() {
    NetworkInfos.setDefault(NETWORK_INFO);
  }

  @AfterClass
  public static void resetNetwork() {
    NetworkInfos.setDefault(null);
  }

  private abstract static class AbstractNemesisBlockTest {

    // basic

    @Test
    public void nemesisBlockCanBeCreated() {
      // Act:
      final Block block = this.loadNemesisBlock();

      // Assert:
      Assert.assertThat(
          block.getSigner().getAddress(), IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAddress()));
      Assert.assertThat(block.getType(), IsEqual.equalTo(-1));
      Assert.assertThat(block.getVersion(), IsEqual.equalTo(EXPECTED_VERSION));
      Assert.assertThat(block.getTimeStamp(), IsEqual.equalTo(TimeInstant.ZERO));

      // 2 multisig aggregate transactions
      Assert.assertThat(
          block.getTotalFee(), IsEqual.equalTo(EXPECTED_MULTISIG_AGGREGATE_FEE.multiply(2)));
      Assert.assertThat(block.getPreviousBlockHash(), IsEqual.equalTo(Hash.ZERO));
      Assert.assertThat(block.getHeight(), IsEqual.equalTo(BlockHeight.ONE));
      Assert.assertThat(block.getTransactions().size(), IsEqual.equalTo(NUM_NEMESIS_TRANSACTIONS));

      Assert.assertThat(block.getDifficulty(), IsEqual.equalTo(BlockDifficulty.INITIAL_DIFFICULTY));
      Assert.assertThat(block.getGenerationHash(), IsNull.notNullValue());
    }

    @Test
    public void nemesisBlockIsVerifiable() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      Assert.assertThat(block.verify(), IsEqual.equalTo(true));
    }

    @Test
    public void nemesisTransactionsAreVerifiable() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      for (final Transaction transaction : block.getTransactions()) {
        Assert.assertThat(transaction.verify(), IsEqual.equalTo(true));
      }
    }

    @Test
    public void nemesisTransactionsHaveCorrectFees() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      for (final Transaction transaction : block.getTransactions()) {
        final Amount expectedFee =
            TransactionTypes.TRANSFER == transaction.getType()
                ? Amount.ZERO
                : NemGlobals.getTransactionFeeCalculator().calculateMinimumFee(transaction);
        Assert.assertThat(transaction.getFee(), IsEqual.equalTo(expectedFee));
      }
    }

    @Test
    public void nemesisAddressesAreValid() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Act:
      final Set<Address> allAddresses =
          block
              .getTransactions()
              .stream()
              .flatMap(t -> t.getAccounts().stream().map(Account::getAddress))
              .collect(Collectors.toSet());

      // Assert:
      for (final Address address : allAddresses) {
        Assert.assertThat(address.toString(), address.isValid(), IsEqual.equalTo(true));
      }
    }

    @Test
    public void nemesisTransactionSignersHavePublicKeys() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Act:
      final Set<Address> signerAddresses =
          block
              .getTransactions()
              .stream()
              .map(t -> t.getSigner().getAddress())
              .collect(Collectors.toSet());

      // Assert:
      for (final Address address : signerAddresses) {
        Assert.assertThat(address.getPublicKey(), IsNull.notNullValue());
      }
    }

    // endregion

    // region constants

    @Test
    public void amountConstantIsConsistentWithNemesisBlock() {
      // Act:
      Amount totalAmount = Amount.ZERO;
      final Block block = this.loadNemesisBlock();
      for (final Transaction transaction : block.getTransactions()) {
        if (transaction instanceof TransferTransaction) {
          totalAmount = totalAmount.add(((TransferTransaction) transaction).getAmount());
        }
      }

      // Assert:
      Assert.assertThat(totalAmount, IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAmount()));
    }

    @Test
    public void addressConstantIsConsistentWithNemesisBlock() {
      // Arrange:
      final Block block = this.loadNemesisBlock();
      final Address blockAddress = block.getSigner().getAddress();

      // Assert:
      Assert.assertThat(blockAddress, IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAddress()));
      Assert.assertThat(
          blockAddress.getPublicKey(),
          IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAddress().getPublicKey()));
      Assert.assertThat(blockAddress.getPublicKey(), IsNull.notNullValue());
    }

    @Test
    public void generationHashConstantIsConsistentWithNemesisBlock() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      Assert.assertThat(
          block.getGenerationHash(), IsEqual.equalTo(NEMESIS_BLOCK_INFO.getGenerationHash()));
    }

    // endregion

    protected abstract Block loadNemesisBlock(final MockAccountLookup accountLookup);

    protected Block loadNemesisBlock() {
      return this.loadNemesisBlock(new MockAccountLookup());
    }
  }

  // region basic

  public static class ResourceNemesisBlockTest extends AbstractNemesisBlockTest {

    @Override
    protected Block loadNemesisBlock(final MockAccountLookup accountLookup) {
      return NemesisBlock.fromResource(
          NEMESIS_BLOCK_INFO, new DeserializationContext(accountLookup));
    }
  }

  public static class BinaryNemesisBlockTest extends AbstractNemesisBlockTest {

    @Test
    public void nemesisBlockCannotBeLoadedFromBlobWithIncorrectType() {
      // Arrange (set type to 1):
      final byte[] buffer = loadNemesisBlockBlobObject();
      buffer[0] = 1;
      buffer[1] = 0;
      buffer[2] = 0;
      buffer[3] = 0;

      // Act:
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO, buffer, new DeserializationContext(new MockAccountLookup())),
          IllegalArgumentException.class);
    }

    @Test
    public void nemesisBlockCannotBeLoadedFromInvalidBlob() {
      // Arrange:
      final byte[] buffer = loadNemesisBlockBlobObject();
      final byte[] badBuffer1 =
          ByteBuffer.allocate(3 + buffer.length).put("bad".getBytes()).put(buffer).array();
      final byte[] badBuffer2 =
          ByteBuffer.allocate(3 + buffer.length)
              .put(Arrays.copyOfRange(buffer, 0, 100))
              .put("bad".getBytes())
              .put(Arrays.copyOfRange(buffer, 100, buffer.length))
              .array();

      // Act:
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO,
                  badBuffer1,
                  new DeserializationContext(new MockAccountLookup())),
          IllegalArgumentException.class);
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO,
                  badBuffer2,
                  new DeserializationContext(new MockAccountLookup())),
          SerializationException.class);
    }

    @Override
    protected Block loadNemesisBlock(final MockAccountLookup accountLookup) {
      final byte[] blob = loadNemesisBlockBlobObject();
      return NemesisBlock.fromBlobObject(
          NEMESIS_BLOCK_INFO, blob, new DeserializationContext(accountLookup));
    }

    private static byte[] loadNemesisBlockBlobObject() {
      try (final InputStream fin =
          NemesisBlock.class
              .getClassLoader()
              .getResourceAsStream(NEMESIS_BLOCK_INFO.getDataFileName())) {
        return IOUtils.toByteArray(fin);
      } catch (final IOException e) {
        throw new IllegalStateException(
            "unexpected exception was thrown when parsing nemesis block resource");
      }
    }
  }
}
 protected void setDetailedStateInternal(NetworkInfo.DetailedState state) {
   mNetworkInfo.setDetailedState(state, null, null);
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {

      // UI update to indicate wifi p2p status.
      int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
      if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
        // Wifi Direct mode is enabled
        synCarnet.syncService.setIsWifiP2pEnabled(true);
      } else {
        synCarnet.syncService.setIsWifiP2pEnabled(false);
        synCarnet.syncService.setConnected(false);
        progressDialog = synCarnet.syncService.getProgressDialog();
        if (progressDialog != null && progressDialog.isShowing()) {
          progressDialog.dismiss();
        }
        Toast.makeText(this.synCarnet, synCarnet.getString(R.string.noWifi), Toast.LENGTH_SHORT)
            .show();
      }
    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
      // request available peers from the wifi p2p manager. This is an
      // asynchronous call and the calling activity is notified with a
      // callback on PeerListListener.onPeersAvailable()
      if (manager != null) {
        if (!synCarnet.syncService.isConnected() && synCarnet.syncService.isWifiP2pEnabled())
          manager.requestPeers(channel, peerList);
      }
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

      if (manager == null) {
        return;
      }

      NetworkInfo networkInfo =
          (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

      if (networkInfo.isConnected()) {
        WifiP2pGroup group =
            (WifiP2pGroup) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP);
        if (group != null) {
          ServiceStatic.setDevice(group.getOwner().deviceName, group.getOwner().deviceAddress);
        }

        // we are connected with the other device, request connection
        // info to find group owner IP

        synCarnet.syncService.setConnected(true);
        progressDialog = synCarnet.syncService.getProgressDialog();
        Toast.makeText(
                synCarnet, synCarnet.getString(R.string.connexionSuccessful), Toast.LENGTH_SHORT)
            .show();
        peerList.setIntent(intent);
        manager.requestConnectionInfo(channel, peerList);
        if (!displayPeers) {
          Toast.makeText(synCarnet, synCarnet.getString(R.string.syncing), Toast.LENGTH_SHORT)
              .show();
        }
      } else {
        synCarnet.syncService.setConnected(false);
      }
    }
  }
  @Override
  public LinkQualityInfo getLinkQualityInfo() {
    if (mNetworkInfo == null || mNetworkInfo.getType() == ConnectivityManager.TYPE_NONE) {
      // no data available yet; just return
      return null;
    }

    MobileLinkQualityInfo li = new MobileLinkQualityInfo();

    li.setNetworkType(mNetworkInfo.getType());

    mSamplingDataTracker.setCommonLinkQualityInfoFields(li);

    if (mNetworkInfo.getSubtype() != TelephonyManager.NETWORK_TYPE_UNKNOWN) {
      li.setMobileNetworkType(mNetworkInfo.getSubtype());

      NetworkDataEntry entry = getNetworkDataEntry(mNetworkInfo.getSubtype());
      if (entry != null) {
        li.setTheoreticalRxBandwidth(entry.downloadBandwidth);
        li.setTheoreticalRxBandwidth(entry.uploadBandwidth);
        li.setTheoreticalLatency(entry.latency);
      }

      if (mSignalStrength != null) {
        li.setNormalizedSignalStrength(
            getNormalizedSignalStrength(li.getMobileNetworkType(), mSignalStrength));
      }
    }

    SignalStrength ss = mSignalStrength;
    if (ss != null) {

      li.setRssi(ss.getGsmSignalStrength());
      li.setGsmErrorRate(ss.getGsmBitErrorRate());
      li.setCdmaDbm(ss.getCdmaDbm());
      li.setCdmaEcio(ss.getCdmaEcio());
      li.setEvdoDbm(ss.getEvdoDbm());
      li.setEvdoEcio(ss.getEvdoEcio());
      li.setEvdoSnr(ss.getEvdoSnr());
      li.setLteSignalStrength(ss.getLteSignalStrength());
      li.setLteRsrp(ss.getLteRsrp());
      li.setLteRsrq(ss.getLteRsrq());
      li.setLteRssnr(ss.getLteRssnr());
      li.setLteCqi(ss.getLteCqi());
    }

    if (VDBG) {
      Slog.d(
          TAG,
          "Returning LinkQualityInfo with"
              + " MobileNetworkType = "
              + String.valueOf(li.getMobileNetworkType())
              + " Theoretical Rx BW = "
              + String.valueOf(li.getTheoreticalRxBandwidth())
              + " gsm Signal Strength = "
              + String.valueOf(li.getRssi())
              + " cdma Signal Strength = "
              + String.valueOf(li.getCdmaDbm())
              + " evdo Signal Strength = "
              + String.valueOf(li.getEvdoDbm())
              + " Lte Signal Strength = "
              + String.valueOf(li.getLteSignalStrength()));
    }

    return li;
  }