android.net.wifi.WifiInfo Java Examples

The following examples show how to use android.net.wifi.WifiInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProvisioningValuesLoader.java    From android-NfcProvisioning with Apache License 2.0 6 votes vote down vote up
private void loadSystemValues(HashMap<String, String> values) {
    Context context = getContext();
    //noinspection deprecation
    putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME,
            "com.example.android.deviceowner");
    if (Build.VERSION.SDK_INT >= 23) {
        putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME,
                "com.example.android.deviceowner/.DeviceOwnerReceiver");
    }
    putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_LOCALE,
            CompatUtils.getPrimaryLocale(context.getResources().getConfiguration()).toString());
    putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE,
            TimeZone.getDefault().getID());
    if (!values.containsKey(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Activity.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (info.getNetworkId() != -1) { // Connected to network
            values.put(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID,
                    trimSsid(info.getSSID()));
        }
    }
}
 
Example #2
Source File: NetworkUtil.java    From ShareBox with Apache License 2.0 6 votes vote down vote up
/**
 * result[0] is self ip,result[1] is host ip,result[2] is isWifiEnable,true or false.
 */
public static ArrayList<String> getWifiHostAndSelfIP(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    String isWifiEnable;
    if (!wifiManager.isWifiEnabled()) {
        isWifiEnable = "false";
    } else
        isWifiEnable = "true";
    ArrayList<String> result = new ArrayList<>();
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    String IPAddress = intToIp(wifiInfo.getIpAddress());
    result.add(IPAddress);

    DhcpInfo dhcpinfo = wifiManager.getDhcpInfo();
    String serverAddress = intToIp(dhcpinfo.serverAddress);
    result.add(serverAddress);

    result.add(isWifiEnable);
    return result;
}
 
Example #3
Source File: MacAddressUtils.java    From CacheEmulatorChecker with Apache License 2.0 6 votes vote down vote up
public static String getConnectedWifiMacAddress(Application context) {
    String connectedWifiMacAddress = null;
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    List<ScanResult> wifiList;

    if (wifiManager != null) {
        wifiList = wifiManager.getScanResults();
        WifiInfo info = wifiManager.getConnectionInfo();
        if (wifiList != null && info != null) {
            for (int i = 0; i < wifiList.size(); i++) {
                ScanResult result = wifiList.get(i);
                if (!TextUtils.isEmpty(info.getBSSID()) && info.getBSSID().equals(result.BSSID)) {
                    connectedWifiMacAddress = result.BSSID;
                }
            }
        }
    }
    return connectedWifiMacAddress;
}
 
Example #4
Source File: SetupFlowTest.java    From spark-setup-android with Apache License 2.0 6 votes vote down vote up
private void mockDeviceDiscoveryResult(String ssid) {
    ScanResult scanResult = mock(ScanResult.class);
    scanResult.SSID = ssid;
    scanResult.capabilities = "WEP";
    //mock wifi wrapper to return fake photon device in scan results
    List<ScanResult> scanResultList = new ArrayList<>();
    scanResultList.add(scanResult);
    when(wifiFacade.getScanResults()).thenReturn(scanResultList);
    //create fake wifi info object for fake photon device
    WifiInfo wifiInfo = mock(WifiInfo.class);
    when(wifiInfo.getSSID()).thenReturn(ssid);
    when(wifiInfo.getNetworkId()).thenReturn(5);
    //mock wifi wrapper to return fake photon device as "connected" network
    when(wifiFacade.getCurrentlyConnectedSSID()).thenReturn(SSID.from(ssid));
    when(wifiFacade.getConnectionInfo()).thenReturn(wifiInfo);
    //mock device discovery process worker to do nothing (would throw exception),
    //doing nothing would mean successful connection to ap
    try {
        doNothing().when(discoverProcessWorker).doTheThing();
    } catch (SetupStepException e) {
        e.printStackTrace();
    }
}
 
Example #5
Source File: ThetaDeviceDetectionFromAccessPoint.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
    String action = intent.getAction();
    if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
        WifiManager wifiMgr = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        if (wifiInfo != null) {
            onNetworkChanged(wifiInfo);
        }
    } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
        int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
        switch (state) {
            case WifiManager.WIFI_STATE_DISABLED:
                onWiFiDisabled();
                break;
            case WifiManager.WIFI_STATE_ENABLED:
                onWiFiEnabled();
                break;
            default:
                break;
        }
    }
}
 
Example #6
Source File: JoH.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static String getWifiSSID() {
    try {
        final WifiManager wifi_manager = (WifiManager) xdrip.getAppContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi_manager.isWifiEnabled()) {
            final WifiInfo wifiInfo = wifi_manager.getConnectionInfo();
            if (wifiInfo != null) {
                final NetworkInfo.DetailedState wifi_state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
                if (wifi_state == NetworkInfo.DetailedState.CONNECTED
                        || wifi_state == NetworkInfo.DetailedState.OBTAINING_IPADDR
                        || wifi_state == NetworkInfo.DetailedState.CAPTIVE_PORTAL_CHECK) {
                    String ssid = wifiInfo.getSSID();
                    if (ssid.equals("<unknown ssid>")) return null; // WifiSsid.NONE;
                    if (ssid.charAt(0) == '"') ssid = ssid.substring(1);
                    if (ssid.charAt(ssid.length() - 1) == '"')
                        ssid = ssid.substring(0, ssid.length() - 1);
                    return ssid;
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Got exception in getWifiSSID: " + e);
    }
    return null;
}
 
Example #7
Source File: SignalInfo.java    From MobileInfo with Apache License 2.0 6 votes vote down vote up
/**
 * wifi
 *
 * @param mContext
 * @return
 */
private static void getDetailsWifiInfo(Context mContext, SignalBean signalBean) {
    try {
        WifiInfo mWifiInfo = getWifiInfo(mContext);
        int ip = mWifiInfo.getIpAddress();
        String strIp = "" + (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 24) & 0xFF);
        signalBean.setBssid(mWifiInfo.getBSSID());
        signalBean.setSsid(mWifiInfo.getSSID().replace("\"", ""));
        signalBean.setnIpAddress(strIp);
        signalBean.setMacAddress(getMac(mContext));
        signalBean.setNetworkId(mWifiInfo.getNetworkId());
        signalBean.setLinkSpeed(mWifiInfo.getLinkSpeed() + "Mbps");
        int rssi = mWifiInfo.getRssi();
        signalBean.setRssi(rssi);
        signalBean.setLevel(calculateSignalLevel(rssi));
        isWifiProxy(mContext, signalBean);
        signalBean.setSupplicantState(mWifiInfo.getSupplicantState().name());
        signalBean.setnIpAddressIpv6(getNetIP());
    } catch (Exception e) {
        Log.i(TAG, e.toString());
    }

}
 
Example #8
Source File: DownloadService.java    From rcloneExplorer with MIT License 6 votes vote down vote up
private boolean checkWifiOnAndConnected() {
    WifiManager wifiMgr = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

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

    if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON

        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        return wifiInfo.getNetworkId() != -1;
    }
    else {
        return false; // Wi-Fi adapter is OFF
    }
}
 
Example #9
Source File: Utils.java    From HJMirror with MIT License 6 votes vote down vote up
/**
 * wifi获取ip
 */
public String getIp(Application context) {
    try {
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            return null;
        }
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    } catch (Exception e) {

    }
    return null;
}
 
Example #10
Source File: WifiBase.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
/**
 * Start to connect to a specific wifi network
 */
private void connectToSpecificNetwork() {
    final WifiManager wifi = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiInfo wifiInfo = wifi.getConnectionInfo();
    if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(getWifiSSID())) {
        return;
    }
    else {
        wifi.disconnect();
    }
    progressDialog = ProgressDialog.show(getContext(), getContext().getString(R.string.connecting), String.format(getContext().getString(R.string.connecting_to_wifi), getWifiSSID()));
    taskHandler = worker.schedule(new TimeoutTask(), getSecondsTimeout(), TimeUnit.SECONDS);
    scanReceiver = new ScanReceiver();
    getContext().registerReceiver(scanReceiver
            , new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifi.startScan();
}
 
Example #11
Source File: DeviceUtil.java    From SimpleProject with MIT License 6 votes vote down vote up
/**
 * 获取手机的Mac地址
 * @param context
 * @return
 */
@SuppressLint("MissingPermission")
public static String getMacAddress(Context context) {
	String macAddress = "";
	WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	if (wifiManager != null) {
		try {
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			macAddress = wifiInfo != null ? wifiInfo.getMacAddress() : "";
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	return macAddress;
}
 
Example #12
Source File: DeviceInfo.java    From Cangol-appcore with Apache License 2.0 6 votes vote down vote up
public static int getWifiRssi(Context context) {
    int asu = 85;
    try {
        final NetworkInfo network = ((ConnectivityManager) context.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (network != null && network.isAvailable() && network.isConnected()) {
            final int type = network.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                final WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

                final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo != null) {
                    asu = wifiInfo.getRssi();
                }
            }
        }
    } catch (Exception e) {
        Log.e("getWifiRssi", "" + e.getMessage(), e);
    }
    return asu;
}
 
Example #13
Source File: WifiBaseActivity.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
/**
 * Start to connect to a specific wifi network
 */
private void connectToSpecificNetwork() {
    final WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiInfo wifiInfo = wifi.getConnectionInfo();
    if (networkInfo.isConnected() && wifiInfo.getSSID().replace("\"", "").equals(getWifiSSID())) {
        return;
    }
    else {
        wifi.disconnect();
    }
    progressDialog = ProgressDialog.show(this, getString(R.string.connecting), String.format(getString(R.string.connecting_to_wifi), getWifiSSID()));
    taskHandler = worker.schedule(new TimeoutTask(), getSecondsTimeout(), TimeUnit.SECONDS);
    scanReceiver = new ScanReceiver();
    registerReceiver(scanReceiver
            , new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifi.startScan();
}
 
Example #14
Source File: Utils.java    From RPiCameraViewer with MIT License 6 votes vote down vote up
public static String getNetworkName()
{
	String ssid = "";
	WifiManager manager = (WifiManager)App.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
	if (manager.isWifiEnabled())
	{
		WifiInfo wifiInfo = manager.getConnectionInfo();
		if (wifiInfo != null)
		{
			NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
			if (state == NetworkInfo.DetailedState.CONNECTED || state == NetworkInfo.DetailedState.OBTAINING_IPADDR)
			{
				ssid = wifiInfo.getSSID();
				if (ssid == null) ssid = "";
				ssid = ssid.replaceAll("^\"|\"$", "");
				if (ssid.equals("<unknown ssid>"))
				{
					ssid = App.getStr(R.string.unknown_network);
				}
			}
		}
	}
	return ssid;
}
 
Example #15
Source File: Util.java    From Leanplum-Android-SDK with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(ACCESS_WIFI_STATE_PERMISSION)
private static String getWifiMacAddressHash(Context context) {
  String logPrefix = "Skipping wifi device id; ";
  if (context.checkCallingOrSelfPermission(ACCESS_WIFI_STATE_PERMISSION) !=
      PackageManager.PERMISSION_GRANTED) {
    Log.v(logPrefix + "no wifi state permissions.");
    return null;
  }
  try {
    WifiManager manager = (WifiManager) context.getApplicationContext()
        .getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = manager.getConnectionInfo();
    if (wifiInfo == null) {
      Log.i(logPrefix + "null WifiInfo.");
      return null;
    }
    @SuppressLint("HardwareIds")
    String macAddress = wifiInfo.getMacAddress();
    if (macAddress == null || macAddress.isEmpty()) {
      Log.i(logPrefix + "no mac address returned.");
      return null;
    }
    if (Constants.INVALID_MAC_ADDRESS.equals(macAddress)) {
      // Note(ed): this is the expected case for Marshmallow and later, as they return
      // INVALID_MAC_ADDRESS; we intend to fall back to the Android id for Marshmallow devices.
      Log.v(logPrefix + "Marshmallow and later returns a fake MAC address.");
      return null;
    }
    @SuppressLint("HardwareIds")
    String deviceId = md5(wifiInfo.getMacAddress());
    Log.v("Using wifi device id: " + deviceId);
    return checkDeviceId("mac address", deviceId);
  } catch (Exception e) {
    Log.w("Error getting wifi MAC address.");
  }
  return null;
}
 
Example #16
Source File: PhoneWifiHelper.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the unquoted name (SSID) of the currently active WiFi network or null if no network
 * is currently active or if the connection cannot be determined.
 *
 * @param context
 * @return
 */
public static String getCurrentWifiSsid (Context context) {
    WifiInfo wifiInfo = getCurrentWifiNetwork(context);

    if (wifiInfo != null && !StringUtils.isEmpty(wifiInfo.getSSID())) {
        return getUnquotedSsid(wifiInfo.getSSID());
    }

    return null;
}
 
Example #17
Source File: UENavigationFragmentActivity.java    From Auie with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	WifiInfo info = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo();
	if (info.getBSSID() == null) {
		mNavigationView.hideWIFI();
	}else {
		mNavigationView.showWIFI();
		mNavigationView.setWIFI(WifiManager.calculateSignalLevel(info.getRssi(), 5));
	}
}
 
Example #18
Source File: WifiFacade.java    From particle-android with Apache License 2.0 5 votes vote down vote up
@Nullable
public SSID getCurrentlyConnectedSSID() {
    WifiInfo connectionInfo = getConnectionInfo();
    if (connectionInfo == null) {
        log.w("getCurrentlyConnectedSSID(): WifiManager.getConnectionInfo() returned null");
        return null;
    } else {
        SSID ssid = SSID.from(connectionInfo);
        log.d("Currently connected to: " + ssid +
                ", supplicant state: " + connectionInfo.getSupplicantState());
        return ssid;
    }
}
 
Example #19
Source File: NetworkMonitorAutoDetect.java    From webrtc_android with MIT License 5 votes vote down vote up
String getWifiSSID() {
  final Intent intent = context.registerReceiver(
      null, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
  if (intent != null) {
    final WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
    if (wifiInfo != null) {
      final String ssid = wifiInfo.getSSID();
      if (ssid != null) {
        return ssid;
      }
    }
  }
  return "";
}
 
Example #20
Source File: RxDeviceTool.java    From RxTools-master with Apache License 2.0 5 votes vote down vote up
/**
 * 获取设备MAC地址
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
 *
 * @param context 上下文
 * @return MAC地址
 */
public static String getMacAddress(Context context) {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    if (info != null) {
        String macAddress = info.getMacAddress();
        if (macAddress != null) {
            return macAddress.replace(":", "");
        }
    }
    return null;
}
 
Example #21
Source File: NetInfo.java    From evercam-android with GNU Affero General Public License v3.0 5 votes vote down vote up
public NetInfo(Context context) {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (isWifiConnected(context)) {
        WifiInfo wifiInfo = wifi.getConnectionInfo();
        localIp = IpTranslator.getIpFromIntSigned(wifiInfo.getIpAddress());
        netmaskIp = IpTranslator.getIpFromIntSigned(wifi.getDhcpInfo().netmask);
        gatewayIp = IpTranslator.getIpFromIntSigned(wifi.getDhcpInfo().gateway);
    }
}
 
Example #22
Source File: DeviceHelper.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
public String getMacAddress() {
	WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	if (wifi == null) {
		return "";
	}

	String mac = null;
	WifiInfo info = wifi.getConnectionInfo();
	if (info != null) {
		mac = info.getMacAddress();
	}
	return (mac == null) ? "" : mac;
}
 
Example #23
Source File: WiFiManagerWrapper.java    From WiFiAnalyzer with GNU General Public License v3.0 5 votes vote down vote up
WifiInfo wiFiInfo() {
    try {
        return wifiManager.getConnectionInfo();
    } catch (Exception e) {
        return null;
    }
}
 
Example #24
Source File: Utils.java    From adbwireless with GNU General Public License v3.0 5 votes vote down vote up
public static boolean checkWifiState(Context context) {
	try {
		WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		if (!mWifiManager.isWifiEnabled() || wifiInfo.getSSID() == null) {
			return false;
		}

		return true;
	} catch (Exception e) {
		return false;
	}
}
 
Example #25
Source File: DemoActivity.java    From OkSocket with MIT License 5 votes vote down vote up
public String getIPAddress() {
    NetworkInfo info = ((ConnectivityManager)
            getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
            try {
                //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }

        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            if (ipAddress == 0) return "未连接wifi";
            return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
                    + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
        }
    } else {
        //当前无网络连接,请在设置中打开网络
        return "当前无网络连接,请在设置中打开网络";
    }
    return "IP获取失败";
}
 
Example #26
Source File: NetworkMonitor.java    From android-utilset with Apache License 2.0 5 votes vote down vote up
/**
 * Returns MAC Address of WiFi Adapter<br>
 * Requires READ_PHONE_STATE, ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE
 * permissions<br>
 * 
 * @return String representing MAC Address of WiFi Adapter; Empty String in
 *         some cases such as No WiFi Adapter is installed or WiFi is turned
 *         off.
 */
public String getWifiMacAddress() {
	WifiManager wifiMan = (WifiManager) context
			.getSystemService(Context.WIFI_SERVICE);
	if (wifiMan != null) {
		WifiInfo wifiInf = wifiMan.getConnectionInfo();
		return wifiInf.getMacAddress();
	}
	return "";
}
 
Example #27
Source File: AndroidUtil.java    From NewsMe with Apache License 2.0 5 votes vote down vote up
/**
 * 获取本地Ip地址
 * 
 * @param context
 * @return
 */
public static String getLocalIpAddress(Context context) {
	WifiManager wifiManager = (WifiManager) context
			.getSystemService(Context.WIFI_SERVICE);
	WifiInfo wifiInfo = wifiManager.getConnectionInfo();
	if (wifiInfo != null && wifiInfo.getIpAddress() != 0) {
		return android.text.format.Formatter.formatIpAddress(wifiInfo
				.getIpAddress());
	} else {
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface intf = en.nextElement();
				Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses();
				while (enumIpAddr.hasMoreElements()) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& inetAddress.getHostAddress().indexOf(":") == -1) {
						String ipAddress = inetAddress.getHostAddress();
						if (!TextUtils.isEmpty(ipAddress)
								&& !ipAddress.contains(":")) {
							return ipAddress;
						}
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	return null;
}
 
Example #28
Source File: StateMachineConnection.java    From timelapse-sony with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void process(StateMachineConnection sm) {
    WifiInfo connectedWifi = sm.mWifiHandler.getConnectedWifi();
    if (connectedWifi != null) {
        sm.mStateRegistry.wifiInfo = connectedWifi;
        sm.setCurrentState(State.WIFI_CONNECTED);
    } else {
        sm.setCurrentState(State.WIFI_DISCONNECTED);
    }
}
 
Example #29
Source File: NetworkChangeReceiver.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
public static EventNetworkChange grabNetworkStatus(final Context context) {
    EventNetworkChange event = new EventNetworkChange();

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) return null;
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    if (activeNetwork != null) {
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
            event.setWifiConnected(true);
            WifiManager wifiManager = (WifiManager) MainApp.instance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
                    event.setSsid(wifiInfo.getSSID());
                }
                if (L.isEnabled(L.CORE))
                    log.debug("NETCHANGE: Wifi connected. SSID: " + event.connectedSsid());
            }
        }

        if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            event.setMobileConnected(true);
            event.setRoaming(activeNetwork.isRoaming());
            if (L.isEnabled(L.CORE))
                log.debug("NETCHANGE: Mobile connected. Roaming: " + event.getRoaming());
        }
    } else {
        if (L.isEnabled(L.CORE))
            log.debug("NETCHANGE: Disconnected.");
    }

    lastEvent = event;
    return event;
}
 
Example #30
Source File: ApplicationContextClient.java    From anetty_client with Apache License 2.0 5 votes vote down vote up
/**
 * 生成Device对象
 * 
 * @param appKey
 * @param appPackage
 * @param deviceId
 * @param imei
 * @return
 */

public Device makeDevice(Context context, String appKey, String appPackage) {

	Device deviceInfo = this.getDeviceInfoByAppPackage(appPackage);
	if (deviceInfo == null || (deviceInfo.getAppKey() != null && !deviceInfo.getAppKey().equals(appKey))) {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();

		String macAddress = null;
		WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
		if (null != info) {
			macAddress = info.getMacAddress();
		}

		String deviceId = Md5Util.toMD5(SystemConsts.CHANNEL + appKey + macAddress + imei);
		if (deviceInfo == null) {
			deviceInfo = new Device();
		}
		deviceInfo.setAppKey(appKey);
		deviceInfo.setAppPackage(appPackage);
		deviceInfo.setDeviceId(deviceId);
		deviceInfo.setImei(imei);
		deviceInfo.setIsOnline(DEVICE_OFFLINE);
	}
	return deviceInfo;
}