Java Code Examples for android.net.wifi.WifiManager

The following examples show how to use android.net.wifi.WifiManager. These examples are extracted from open source projects. 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 Project: PhoneProfilesPlus   Source File: WifiApManager.java    License: Apache License 2.0 7 votes vote down vote up
@SuppressLint("PrivateApi")
WifiApManager(Context context) throws SecurityException, NoSuchMethodException {
    mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (mWifiManager != null)
        wifiApEnabled = mWifiManager.getClass().getDeclaredMethod("isWifiApEnabled");
    /*if (PPApplication.logEnabled()) {
        PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-mWifiManager=" + mWifiManager);
        PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-wifiApEnabled=" + wifiApEnabled);
    }*/
    if (Build.VERSION.SDK_INT >= 26) {
        mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        packageName = context.getPackageName();
    }
    else {
        if (mWifiManager != null) {
            wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration"/*,null*/);
            //wifiApState = mWifiManager.getClass().getMethod("getWifiApState");
        }
        /*if (PPApplication.logEnabled()) {
            PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-wifiControlMethod=" + wifiControlMethod);
            PPApplication.logE("$$$ WifiAP", "WifiApManager.WifiApManager-wifiApConfigurationMethod=" + wifiApConfigurationMethod);
        }*/
    }
}
 
Example 2
Source Project: WifiUtils   Source File: ConnectorUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
private static boolean checkForExcessOpenNetworkAndSave(@NonNull final ContentResolver resolver, @NonNull final WifiManager wifiMgr) {
    final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
    sortByPriority(configurations);

    boolean modified = false;
    int tempCount = 0;
    final int numOpenNetworksKept = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
            ? Settings.Secure.getInt(resolver, Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT, 10)
            : Settings.Secure.getInt(resolver, Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10);

    for (int i = configurations.size() - 1; i >= 0; i--) {
        final WifiConfiguration config = configurations.get(i);
        if (Objects.equals(ConfigSecurities.SECURITY_NONE, ConfigSecurities.getSecurity(config))) {
            tempCount++;
            if (tempCount >= numOpenNetworksKept) {
                modified = true;
                wifiMgr.removeNetwork(config.networkId);
            }
        }
    }
    return !modified || wifiMgr.saveConfiguration();

}
 
Example 3
Source Project: Android   Source File: WifiConnector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
   public void onReceive(Context context, Intent intent) {
	
if (!WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
           return;
    }				
	
       mLock.lock();
	
       WifiInfo info = mWifiManager.getConnectionInfo();
       if ( info.getNetworkId()==mNetworkID && info.getSupplicantState() == SupplicantState.COMPLETED ) {
           mIsConnnected = true;
           mCondition.signalAll();			
}
	
       mLock.unlock();	
   }
 
Example 4
Source Project: PrivacyStreams   Source File: WifiApListProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void provide() {

    WifiManager wifiMgr = (WifiManager) this.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    if(wifiMgr.isWifiEnabled()) {
        Log.e("wifi","enabled");
        this.getContext().registerReceiver(this.wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        wifiMgr.startScan();
    }
    else{
        Log.e("wifi","not enabled");
        this.finish();
    }

}
 
Example 5
Source Project: YouTube-In-Background   Source File: BackgroundAudioService.java    License: MIT License 6 votes vote down vote up
@SuppressLint("WifiManagerPotentialLeak")
@Override
public void onCreate()
{
    super.onCreate();
    context = getApplicationContext();
    currentVideo = new YouTubeVideo();
    audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    currentVideoPosition = -1;
    mediaButtonFilter.setPriority(1000); //this line sets receiver priority

    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    this.wifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "YTinBG_lock");
    initMediaSessions();
    initPhoneCallListener();
}
 
Example 6
Source Project: Nimingban   Source File: Settings.java    License: Apache License 2.0 6 votes vote down vote up
public static String getMacFeedId() {
    WifiManager wifi = (WifiManager) sContext.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    if (info == null) {
        return null;
    }

    String mac = info.getMacAddress();
    if (mac == null) {
        return null;
    }

    String id;
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(mac.getBytes());
        id = bytesToHexString(digest.digest());
    } catch (NoSuchAlgorithmException e) {
        id = String.valueOf(mac.hashCode());
    }

    return id;
}
 
Example 7
/**
 * Start connecting to specific wifi network
 */
protected void handleWIFI() {
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    if (!wifi.isWifiEnabled()) {
        showWifiDisabledDialog();
    }
    else {
        if (!permisionLocationOn()) {
            setLocationPermission();
        } else {
            if (checkLocationTurnOn()) {
                connectToSpecificNetwork();
            }
        }
    }
}
 
Example 8
Source Project: cordova-plugin-wifi   Source File: WifiAdmin.java    License: MIT License 6 votes vote down vote up
private PluginResult executeEnableWifi(JSONArray inputs, CallbackContext callbackContext) {
  	Log.w(LOGTAG, "executeEnableWifi");

Context context = cordova.getActivity().getApplicationContext();
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

boolean toEnable = true;
try {
	toEnable = inputs.getBoolean( 0 );
} catch (JSONException e) {
      Log.w(LOGTAG, String.format("Got JSON Exception: %s", e.getMessage()));
      return new PluginResult(Status.JSON_EXCEPTION);
}
      
wifiManager.setWifiEnabled( toEnable );
callbackContext.success();

  	return null;
  }
 
Example 9
Source Project: 365browser   Source File: PlatformNetworksManager.java    License: Apache License 2.0 6 votes vote down vote up
static VisibleWifi getConnectedWifi(Context context, WifiManager wifiManager) {
    if (!hasLocationAndWifiPermission(context)) {
        return VisibleWifi.NO_WIFI_INFO;
    }
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo == null) {
        return VisibleWifi.NO_WIFI_INFO;
    }
    String ssid = wifiInfo.getSSID();
    if (ssid == null || UNKNOWN_SSID.equals(ssid)) {
        // No SSID.
        ssid = null;
    } else {
        // Remove double quotation if ssid has double quotation.
        if (ssid.startsWith("\"") && ssid.endsWith("\"") && ssid.length() > 2) {
            ssid = ssid.substring(1, ssid.length() - 1);
        }
    }
    String bssid = wifiInfo.getBSSID();
    // It's connected, so use current time.
    return VisibleWifi.create(ssid, bssid, null, sTimeProvider.getCurrentTime());
}
 
Example 10
Source Project: RoMote   Source File: ConnectivityActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    if (!mNetworkMonitor.isConnectedToiWiFi() &&
            !mNetworkMonitor.isMobileAccessPointOn() &&
            mDialog == null) {
        showDialog();
    }

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);

    registerReceiver(mConnectivityReceiver, intentFilter);
}
 
Example 11
Source Project: android_9.0.0_r45   Source File: Tethering.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context content, Intent intent) {
    final String action = intent.getAction();
    if (action == null) return;

    if (action.equals(UsbManager.ACTION_USB_STATE)) {
        handleUsbAction(intent);
    } else if (action.equals(CONNECTIVITY_ACTION)) {
        handleConnectivityAction(intent);
    } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
        handleWifiApAction(intent);
    } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
        mLog.log("OBSERVED configuration changed");
        updateConfiguration();
    }
}
 
Example 12
Source Project: RPiCameraViewer   Source File: Utils.java    License: MIT License 6 votes vote down vote up
public static String getLocalIpAddress()
{
	String address = "";
	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)
			{
				int ip = wifiInfo.getIpAddress();
				address = Formatter.formatIpAddress(ip);
			}
		}
	}
	return address;
}
 
Example 13
Source Project: AndroidWallet   Source File: AppNetworkMgr.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 过滤扫描结果
 *
 * @param context
 * @param bssid
 * @return
 */
public static ScanResult getScanResultsByBSSID(Context context, String bssid) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    ScanResult scanResult = null;
    boolean f = wifiManager.startScan();
    if (!f) {
        getScanResultsByBSSID(context, bssid);
    }
    List<ScanResult> list = wifiManager.getScanResults();
    if (list != null) {
        for (int i = 0; i < list.size(); i++) {
            scanResult = list.get(i);
            if (scanResult.BSSID.equals(bssid)) {
                break;
            }
        }
    }
    return scanResult;
}
 
Example 14
Source Project: GLEXP-Team-onebillion   Source File: OBConnectionManager.java    License: Apache License 2.0 6 votes vote down vote up
public String getCurrentWifiSSID()
{
    WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo ();
    String ssid = info.getSSID();
    if (info.getSupplicantState() != SupplicantState.COMPLETED)
    {
        MainActivity.log("OBConnectionManager:getCurrentWifiSSID. not connected to current wifi. returning null");
        return null;
    }
    if (ssid.charAt(0) == '"' && ssid.charAt(ssid.length() - 1) == '"')
    {
        return ssid.substring(1, ssid.length() - 1);
    }
    else
    {
        return ssid;
    }
}
 
Example 15
Source Project: PacketSender-Android   Source File: DataStorage.java    License: MIT License 6 votes vote down vote up
public static boolean isWifiActive(Context ctx)
{
    WifiManager wifi = (WifiManager) ctx.getSystemService(ctx.WIFI_SERVICE);

    if(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED )
    {

        return false;
    } else {

        if(getIP(ctx).equalsIgnoreCase("0.0.0.0"))
        {
            return false;

        } else {
            return true;
        }


    }
}
 
Example 16
Source Project: MiBandDecompiled   Source File: ai.java    License: Apache License 2.0 6 votes vote down vote up
protected final String p()
{
    if (m == null && a != null)
    {
        d = (WifiManager)a.getSystemService("wifi");
        if (d != null && d.getConnectionInfo() != null)
        {
            m = d.getConnectionInfo().getMacAddress();
            if (m != null && m.length() > 0)
            {
                m = m.replace(":", "");
            }
        }
    }
    if (m != null)
    {
        return m;
    } else
    {
        return "";
    }
}
 
Example 17
Source Project: sync-android   Source File: ReplicationServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setUp() {
    mMockContext = mock(Context.class);
    mMockPreferences = mock(SharedPreferences.class);
    when(mMockContext.getSharedPreferences("com.cloudant.preferences", Context.MODE_PRIVATE)).thenReturn(mMockPreferences);
    when(mMockContext.getPackageName()).thenReturn("cloudant.com.androidtest");
    when(mMockContext.getDir(anyString(), anyInt())).thenReturn(new File("/data/data/cloudant.com.androidtest/files"));
    when(mMockContext.getApplicationContext()).thenReturn(mMockContext);
    mMockPreferencesEditor = mock(SharedPreferences.Editor.class);
    when(mMockPreferences.edit()).thenReturn(mMockPreferencesEditor);
    mMockAlarmManager = mock(AlarmManager.class);
    mMockWifiManager = mock(WifiManager.class);
    mMockWifiLock = mock(WifiManager.WifiLock.class);
    mMockReplicationPolicyManager = mock(ReplicationPolicyManager.class);
    mMockReplicators = new Replicator[]{mock(Replicator.class)};
}
 
Example 18
Source Project: AntennaPodSP   Source File: NetworkUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Returns true if the device is connected to Wi-Fi and the Wi-Fi filter for
 * automatic downloads is disabled or the device is connected to a Wi-Fi
 * network that is on the 'selected networks' list of the Wi-Fi filter for
 * automatic downloads and false otherwise.
 */
public static boolean autodownloadNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null) {
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            if (AppConfig.DEBUG)
                Log.d(TAG, "Device is connected to Wi-Fi");
            if (networkInfo.isConnected()) {
                if (!UserPreferences.isEnableAutodownloadWifiFilter()) {
                    if (AppConfig.DEBUG)
                        Log.d(TAG, "Auto-dl filter is disabled");
                    return true;
                } else {
                    WifiManager wm = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wm.getConnectionInfo();
                    List<String> selectedNetworks = Arrays
                            .asList(UserPreferences
                                    .getAutodownloadSelectedNetworks());
                    if (selectedNetworks.contains(Integer.toString(wifiInfo
                            .getNetworkId()))) {
                        if (AppConfig.DEBUG)
                            Log.d(TAG,
                                    "Current network is on the selected networks list");
                        return true;
                    }
                }
            }
        }
    }
    if (AppConfig.DEBUG)
        Log.d(TAG, "Network for auto-dl is not available");
    return false;
}
 
Example 19
Source Project: q-municate-android   Source File: CallActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    intentFilter.addAction(AudioManager.ACTION_HEADSET_PLUG);
    intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
    registerReceiver(wifiStateReceiver, intentFilter);
    registerReceiver(audioStreamReceiver, intentFilter);
}
 
Example 20
Source Project: RePlugin-GameSdk   Source File: HWUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取mac地址
 * 
 * @param context
 * @return String
 */
public static String getLocalMacAddress(Context context) {
	WifiManager wifi = (WifiManager) context
			.getSystemService(Context.WIFI_SERVICE);
	WifiInfo info = wifi.getConnectionInfo();
	return info.getMacAddress();
}
 
Example 21
Source Project: TvPlayer   Source File: DeviceUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
    String ret;
    int wifiState = wifiMan.getWifiState();

    wifiMan.setWifiEnabled(true);
    File fl = new File(fileAddressMac);
    FileInputStream fin = new FileInputStream(fl);
    ret = crunchifyGetStringFromStream(fin);
    fin.close();

    boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
    wifiMan.setWifiEnabled(enabled);
    return ret;
}
 
Example 22
Source Project: MiBandDecompiled   Source File: NetworkHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static int getWifiState(Context context)
{
    WifiManager wifimanager = (WifiManager)context.getSystemService("wifi");
    if (wifimanager == null)
    {
        return 4;
    } else
    {
        return wifimanager.getWifiState();
    }
}
 
Example 23
public static boolean aquireWifiMulticast(Context context)
{
	boolean result = false;
	WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
	if(wifiManager != null)
	{
		wifiMulticastLock = wifiManager.createMulticastLock("PdDroidPartyMulticastLock");
		wifiMulticastLock.acquire();
		result = wifiMulticastLock.isHeld();
	}
	return result;
}
 
Example 24
Source Project: BigApp_Discuz_Android   Source File: NetWorkUtils.java    License: Apache License 2.0 5 votes vote down vote up
public NetWorkUtils(Context context) {
    this.context = context;
    mConnectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    isMobileDataEnable = isMobileNetWorkEnabled();
}
 
Example 25
Source Project: TVRemoteIME   Source File: RemoteServer.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static String getLocalIPAddress(Context context){
    WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
    if(ipAddress == 0){
        try {
            Enumeration<NetworkInterface> enumerationNi = NetworkInterface.getNetworkInterfaces();
            while (enumerationNi.hasMoreElements()) {
                NetworkInterface networkInterface = enumerationNi.nextElement();
                String interfaceName = networkInterface.getDisplayName();
                if (interfaceName.equals("eth0") || interfaceName.equals("wlan0")) {
                    Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses();

                    while (enumIpAddr.hasMoreElements()) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            Log.e(IMEService.TAG, "获取本地IP出错", e);
        }
    }else {
        return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    }
    return "0.0.0.0";
}
 
Example 26
Source Project: AndroidModulePattern   Source File: NetworkUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 打开或关闭wifi
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}</p>
 *
 * @param enabled {@code true}: 打开<br>{@code false}: 关闭
 */
public static void setWifiEnabled(boolean enabled) {
    WifiManager wifiManager = (WifiManager) Utils.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (enabled) {
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    } else {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }
}
 
Example 27
Source Project: GLEXP-Team-onebillion   Source File: OBConnectionManager.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isScanningDisabled ()
{
    WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
    if (wifiManager.isScanAlwaysAvailable()) return false;
    //
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter.isDiscovering()) return false;
    //
    return true;
}
 
Example 28
Source Project: GLEXP-Team-onebillion   Source File: OBConnectionManager.java    License: Apache License 2.0 5 votes vote down vote up
public void forgetAllNetworks()
{
    WifiManager wifiManager = (WifiManager) MainActivity.mainActivity.getApplicationContext().getSystemService(MainActivity.WIFI_SERVICE);
    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    //
    for( WifiConfiguration i : list )
    {
        // Please Note: the app cannot make the system forget wifi configurations that were placed by the user or other apps.
        // Just the ones that this app has set.
        wifiManager.removeNetwork(i.networkId);
        wifiManager.saveConfiguration();
    }
}
 
Example 29
@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 Project: DeviceConnect-Android   Source File: DConnectUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Gets the ip address.
 *
 * @param context Context of application
 * @return Returns ip address
 */
public static String getIPAddress(final Context context) {
    Context appContext = context.getApplicationContext();
    WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
    ConnectivityManager cManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network = cManager.getActiveNetworkInfo();
    String en0Ip = null;
    if (network != null) {
        switch (network.getType()) {
            case ConnectivityManager.TYPE_ETHERNET:
                try {
                    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 instanceof Inet4Address
                                    && !inetAddress.getHostAddress().equals("127.0.0.1")) {
                                en0Ip = inetAddress.getHostAddress();
                                break;
                            }
                        }
                    }
                } catch (SocketException e) {
                    Log.e("DConnectUtil", "Get Ethernet IP Error", e);
                }
        }
    }

    if (en0Ip != null) {
        return en0Ip;
    } else {
        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
        return String.format(Locale.getDefault(), "%d.%d.%d.%d",
                (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    }
}