android.net.ConnectivityManager#getNetworkInfo ( )源码实例Demo

下面列出了android.net.ConnectivityManager#getNetworkInfo ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: GOpenSource_AppKit_Android_AS   文件: NetUtils.java
/**
 * 判断当前手机的网络是否可用.
 *
 * @param context
 *            上下文
 * @return boolean 是否连上网络
 * 
 *         *
 */
static public boolean isMobileConnected(Context context) {
	if (context != null) {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (mMobileNetworkInfo != null) {
			if (mMobileNetworkInfo.isAvailable()) {
				return mMobileNetworkInfo.isConnected();
			} else {
				return false;
			}
		}
	}
	return false;
}
 
源代码2 项目: fdroidclient   文件: Preferences.java
/**
 * Some users never use WiFi, this lets us check for that state on first run.
 */
public void setDefaultForDataOnlyConnection(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) {
        return;
    }
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting()) {
        return;
    }
    if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (!wifiNetwork.isConnectedOrConnecting()) {
            preferences.edit().putInt(PREF_OVER_DATA, OVER_NETWORK_ALWAYS).apply();
        }
    }
}
 
源代码3 项目: react-native-wifi-reborn   文件: RNWifiModule.java
/**
 * Returns if the device is currently connected to a WiFi network.
 */
@ReactMethod
public void connectionStatus(final Promise promise) {
    final ConnectivityManager connectivityManager = (ConnectivityManager) getReactApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager == null) {
        promise.resolve(false);
        return;
    }

    NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiInfo == null) {
        promise.resolve(false);
        return;
    }

    promise.resolve(wifiInfo.isConnected());
}
 
源代码4 项目: TelePlus-Android   文件: ConnectionsManager.java
public static boolean isConnectedOrConnectingToWiFi()
{
    try
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(
                Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null)
            return false;

        NetworkInfo netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo.State state = netInfo.getState();
        if (state == NetworkInfo.State.CONNECTED ||
                state == NetworkInfo.State.CONNECTING ||
                state == NetworkInfo.State.SUSPENDED)
            return true;
    }
    catch (Exception e)
    {
        FileLog.e(e);
    }

    return false;
}
 
源代码5 项目: letv   文件: ConnectionChangeReceiver.java
public final void onReceive(Context context, Intent intent) {
    if (context != null) {
        if (a.a == null || a.a.equals("")) {
            new a(context).execute(new Void[0]);
        }
        if (SoundInkInterface.getReceiveSignalAtNoNetWork()) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService("connectivity");
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            connectivityManager.getNetworkInfo(0);
            if (activeNetworkInfo != null) {
                e.a(context);
                this.a = e.c();
                if (this.a.length != 0) {
                    new Thread(new i(this.a)).start();
                }
            }
        }
    }
}
 
源代码6 项目: something.apk   文件: SomePreferences.java
public synchronized static boolean shouldShowAvatars(Context context){
    if(avatarsEnabled){
        return true;
    }else if(avatarsWifi && context != null){
        ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifi == null || wifi.isConnected();
    }
    return false;
}
 
源代码7 项目: MVPArms   文件: DeviceUtils.java
public static boolean netIsConnected(Context context) {
    ConnectivityManager connectMgr = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    //手机网络连接状态
    NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    //WIFI连接状态
    NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    //当前无可用的网络
    return mobNetInfo.isConnected() || wifiNetInfo.isConnected();
}
 
源代码8 项目: android-project-wo2b   文件: DaemonService.java
@Override
public void onReceive(Context context, Intent intent)
{
	String action = intent.getAction();
	Log.I(TAG, "Network state changed, action: " + action);

	ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
	NetworkInfo mobileNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
	NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

	if (mobileNetInfo.isConnected() && wifiNetInfo.isConnected())
	{
		mNetworkStatus = NetworkStatus.CONNECTED;
	}
	else if (mobileNetInfo.isConnected())
	{
		mNetworkStatus = NetworkStatus.MOBILE;
	}
	else if (wifiNetInfo.isConnected())
	{
		Log.I(TAG, "Wifi Network is connected.");
		mNetworkStatus = NetworkStatus.WIFI;
	}
	else if (!mobileNetInfo.isConnected() && !wifiNetInfo.isConnected())
	{
		// 所有网络都没有连接至网络
		mNetworkStatus = NetworkStatus.DISCONNECTED;
	}
	else
	{
		// 所有网络都没有连接至网络
		mNetworkStatus = NetworkStatus.DISCONNECTED;
	}

	Log.D(TAG, "Network status changed: " + mNetworkStatus.name());

	GBus.post(GEvent.NETWORK_STATUS, mNetworkStatus);
}
 
源代码9 项目: MVPAndroidBootstrap   文件: NetworkUtil.java
/**
 * Checks mobile network is active.
 * @param context
 * @return
 */
public static boolean checkMobileIsActive(Context context) {
    ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobile.isConnected()) {
        return true;
    }
    return false;
}
 
源代码10 项目: CrappaLinks   文件: Resolver.java
protected String doInBackground(String... urls) {
    String redirectUrl = urls[0];

    // if there's no connection, fail and return the original URL.
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
            Context.CONNECTIVITY_SERVICE);
    if (connectivityManager.getActiveNetworkInfo() == null) {
        noConnectionError = true;
        return redirectUrl;
    }

    if (useUnshortenIt) {
        return getRedirectUsingLongURL(redirectUrl);
    } else {
        HttpURLConnection.setFollowRedirects(false);
        // Use the cookie manager so that cookies are stored. Useful for some hosts that keep
        // redirecting us indefinitely unless the set cookie is detected.
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);

        // Should we resolve all URLs?
        boolean resolveAll = true;
        NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (resolveAllWhen.equals("NEVER") || (resolveAllWhen.equals("WIFI_ONLY") && !wifiInfo.isConnected()))
            resolveAll = false;

        // Keep trying to resolve the URL until we get a URL that isn't a redirect.
        String finalUrl = redirectUrl;
        while (redirectUrl != null && ((resolveAll) || (RedirectHelper.isRedirect(Uri.parse(redirectUrl).getHost())))) {
            redirectUrl = getRedirect(redirectUrl);
            if (redirectUrl != null) {
                // This should avoid infinite loops, just in case.
                if (redirectUrl.equals(finalUrl))
                    return finalUrl;
                finalUrl = redirectUrl;
            }
        }
        return finalUrl;
    }
}
 
源代码11 项目: SimplifyReader   文件: NetUtils.java
public static boolean isMobileConnected(Context context) {
	if (context != null) {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (mMobileNetworkInfo != null) {
			return mMobileNetworkInfo.isAvailable();
		}
	}
	return false;
}
 
源代码12 项目: foam   文件: Utils.java
/**
 * Check to see if the device is currently connected to a WiFi network.  Used along with
 * {@link FoamApiKeys#wifiOnly()} to only send data over WiFi.
 *
 * @param context Context
 * @return true if the device is currently connected to a WiFi network.
 */
public boolean isOnWifi(Context context) {
    try {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi.isConnected()) {
            return true;
        }
    } catch (Exception ex){
        logIssue("Error checking wifi state", ex);
    }
    return false;
}
 
源代码13 项目: BaseProject   文件: NetHelper.java
public static boolean isWifiNet(Context c) {
    boolean bRet = false;
    ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    @SuppressLint("MissingPermission") NetworkInfo wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (null != wifiInfo && wifiInfo.isConnectedOrConnecting()) {
        bRet = true;
    }
    return bRet;
}
 
源代码14 项目: AndroidUtilCode   文件: NetworkUtils.java
/**
 * Return whether using ethernet.
 * <p>Must hold
 * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
 *
 * @return {@code true}: yes<br>{@code false}: no
 */
@RequiresPermission(ACCESS_NETWORK_STATE)
private static boolean isEthernet() {
    final ConnectivityManager cm =
            (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) return false;
    final NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
    if (info == null) return false;
    NetworkInfo.State state = info.getState();
    if (null == state) return false;
    return state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING;
}
 
源代码15 项目: JianDan_OkHttp   文件: NetWorkUtil.java
/**
 * 判断当前的网络连接方式是否为WIFI
 *
 * @param context
 * @return
 */
public static boolean isWifiConnected(Context context) {
	ConnectivityManager connectivityManager = (ConnectivityManager) context
			.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo wifiNetworkInfo = connectivityManager
			.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	return wifiNetworkInfo.isConnected();
}
 
源代码16 项目: RxAndroidBootstrap   文件: NetworkUtil.java
/**
 * Checks wifi is active.
 * @param context
 * @return
 */
public static boolean checkWifiIsActive(Context context) {
    ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifi.isConnected()) {
        return true;
    }
    return false;
}
 
源代码17 项目: SimplifyReader   文件: NetUtils.java
public static boolean isWifiConnected(Context context) {
	if (context != null) {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (mWiFiNetworkInfo != null) {
			return mWiFiNetworkInfo.isAvailable();
		}
	}
	return false;
}
 
源代码18 项目: android-utilset   文件: NetworkMonitor.java
private void initNetworkState(Context context) {
	ConnectivityManager cm = (ConnectivityManager) context
			.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo niMobile = cm.getNetworkInfo(TYPE_MOBILE);
	NetworkInfo niWifi = cm.getNetworkInfo(TYPE_WIFI);
	NetworkInfo niMms = cm.getNetworkInfo(TYPE_MOBILE_MMS);
	NetworkInfo niSupl = cm.getNetworkInfo(TYPE_MOBILE_SUPL);
	NetworkInfo niDun = cm.getNetworkInfo(TYPE_MOBILE_DUN);
	NetworkInfo niHipri = cm.getNetworkInfo(TYPE_MOBILE_HIPRI);
	NetworkInfo niWimax = cm.getNetworkInfo(TYPE_WIMAX);
	NetworkInfo niBlueTooth = cm.getNetworkInfo(TYPE_BLUETOOTH);
	NetworkInfo niDummy = cm.getNetworkInfo(TYPE_DUMMY);
	NetworkInfo niEthernet = cm.getNetworkInfo(TYPE_ETHERNET);

	if (niWifi != null && niWifi.getState() == State.CONNECTED) {
		state = TYPE_WIFI;
		handleNetworkConnected();
	} else if (niMobile != null && niMobile.getState() == State.CONNECTED) {
		state = TYPE_MOBILE;
		handleNetworkConnected();
	} else if (niBlueTooth != null
			&& niBlueTooth.getState() == State.CONNECTED) {
		state = TYPE_BLUETOOTH;
		handleNetworkConnected();
	} else if (niMms != null && niMms.getState() == State.CONNECTED) {
		state = TYPE_MOBILE_MMS;
		handleNetworkConnected();
	} else if (niSupl != null && niSupl.getState() == State.CONNECTED) {
		state = TYPE_MOBILE_SUPL;
		handleNetworkConnected();
	} else if (niDun != null && niDun.getState() == State.CONNECTED) {
		state = TYPE_MOBILE_DUN;
		handleNetworkConnected();
	} else if (niHipri != null && niHipri.getState() == State.CONNECTED) {
		state = TYPE_MOBILE_HIPRI;
		handleNetworkConnected();
	} else if (niWimax != null && niWimax.getState() == State.CONNECTED) {
		state = TYPE_WIMAX;
		handleNetworkConnected();
	} else if (niDummy != null && niDummy.getState() == State.CONNECTED) {
		state = TYPE_DUMMY;
		handleNetworkConnected();
	} else if (niEthernet != null
			&& niEthernet.getState() == State.CONNECTED) {
		state = TYPE_ETHERNET;
		handleNetworkConnected();
	}
}
 
static public NetworkStatus checkConnectivity(Context context)
{
   NetworkStatus networkStatus = NetworkStatus.NetworkStatusNone;
   RCLogger.d(TAG, "checkConnectivity()");
   ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

   try {
      NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
      if (activeNetwork != null) {
         if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
            RCLogger.w(TAG, "Connectivity status: WIFI");
            networkStatus = NetworkStatus.NetworkStatusWiFi;
         }

         if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE && activeNetwork.isConnected()) {
            RCLogger.w(TAG, "Connectivity status: CELLULAR DATA");
            networkStatus = NetworkStatus.NetworkStatusCellular;
         }

         if (activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET && activeNetwork.isConnected()) {
            RCLogger.w(TAG, "Connectivity status: ETHERNET");
            networkStatus = NetworkStatus.NetworkStatusEthernet;
         }
      }

      // Sadly we cannot use getActiveNetwork right away as its added in API 23 (and we want to support > 21), so let's iterate
      // until we find above activeNetwork
      for (Network network : connectivityManager.getAllNetworks()) {
         NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
         if (networkInfo.isConnected() &&
                 (networkInfo.getType() == activeNetwork.getType()) &&
                 (networkInfo.getSubtype() == activeNetwork.getSubtype()) &&
                 (networkInfo.getExtraInfo().equals(activeNetwork.getExtraInfo()))) {
            LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
            //Log.d("DnsInfo", "iface = " + linkProperties.getInterfaceName());
            //Log.d("DnsInfo", "dns = " + linkProperties.getDnsServers());
            //Log.d("DnsInfo", "domains search = " + linkProperties.getDomains());
            StringBuilder stringBuilder = new StringBuilder();
            for (InetAddress inetAddress : linkProperties.getDnsServers()) {
               if (stringBuilder.length() != 0) {
                  stringBuilder.append(",");
               }
               stringBuilder.append(inetAddress.getHostAddress());
            }
            // From Oreo and above we need to explicitly retrieve and provide the name servers used for our DNS queries.
            // Reason for that is that prior to Oreo underlying dnsjava library for jain-sip.ext (i.e. providing facilities for DNS SRV),
            // used some system properties prefixed 'net.dns1', etc. The problem is that those got removed in Oreo so we have to use
            // alternative means, and that is to use 'dns.server' that 'dnsjava' tries to use before trying 'net.dns1';
            if (stringBuilder.length() != 0) {
               RCLogger.i(TAG, "Updating DNS servers for dnsjava with: " + stringBuilder.toString() + ", i/f: " + linkProperties.getInterfaceName());
               System.setProperty("dns.server", stringBuilder.toString());
            }
            if (linkProperties.getDomains() != null) {
               RCLogger.i(TAG, "Updating DNS search domains for dnsjava with: " + linkProperties.getDomains() + ", i/f: " + linkProperties.getInterfaceName());
               System.setProperty("dns.search", linkProperties.getDomains());
            }
         }
      }
   }
   catch (NullPointerException e) {
      throw new RuntimeException("Failed to retrieve active networks info", e);
   }

   if (networkStatus == NetworkStatus.NetworkStatusNone) {
      RCLogger.w(TAG, "Connectivity status: NONE");
   }

   return networkStatus;
}
 
源代码20 项目: V.FlyoutTest   文件: ConnectivityManagerCompat.java
/**
 * Return the {@link NetworkInfo} that caused the given
 * {@link ConnectivityManager#CONNECTIVITY_ACTION} broadcast. This obtains
 * the current state from {@link ConnectivityManager} instead of using the
 * potentially-stale value from
 * {@link ConnectivityManager#EXTRA_NETWORK_INFO}.
 */
public static NetworkInfo getNetworkInfoFromBroadcast(ConnectivityManager cm, Intent intent) {
    final NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
    return cm.getNetworkInfo(info.getType());
}