Java Code Examples for android.net.ConnectivityManager

The following examples show how to use android.net.ConnectivityManager. 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
public static boolean isRoaming()
{
    try
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
        if (netInfo != null)
            return netInfo.isRoaming();
    }
    catch (Exception e)
    {
        FileLog.e(e);
    }

    return false;
}
 
Example 2
Source Project: memorize   Source File: ConnectionDetector.java    License: MIT License 6 votes vote down vote up
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (NetworkInfo anInfo : info) {
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 3
Source Project: MiBandDecompiled   Source File: Network.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isCtwap(Context context)
{
    if (!"CN".equalsIgnoreCase(((TelephonyManager)context.getSystemService("phone")).getSimCountryIso()))
    {
        return false;
    }
    ConnectivityManager connectivitymanager = (ConnectivityManager)context.getSystemService("connectivity");
    if (connectivitymanager == null)
    {
        return false;
    }
    NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
    if (networkinfo == null)
    {
        return false;
    }
    String s = networkinfo.getExtraInfo();
    if (TextUtils.isEmpty(s) || s.length() < 3)
    {
        return false;
    }
    return s.contains("ctwap");
}
 
Example 4
Source Project: Telegram   Source File: ApplicationLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static boolean isNetworkOnlineFast() {
    try {
        ensureCurrentNetworkGet(false);
        if (currentNetworkInfo == null) {
            return true;
        }
        if (currentNetworkInfo.isConnectedOrConnecting() || currentNetworkInfo.isAvailable()) {
            return true;
        }

        NetworkInfo netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            netInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                return true;
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
        return true;
    }
    return false;
}
 
Example 5
public static GetHomeBundlesRequest of(int limit, int offset, OkHttpClient httpClient,
    Converter.Factory converterFactory, BodyInterceptor bodyInterceptor,
    TokenInvalidator tokenInvalidator, SharedPreferences sharedPreferences,
    WSWidgetsUtils widgetsUtils, BaseRequestWithStore.StoreCredentials storeCredentials,
    String clientUniqueId, boolean isGooglePlayServicesAvailable, String partnerId,
    boolean accountMature, String filters, Resources resources, WindowManager windowManager,
    ConnectivityManager connectivityManager,
    AdsApplicationVersionCodeProvider versionCodeProvider, List<String> packageNames,
    AppBundlesVisibilityManager appBundlesVisibilityManager) {
  return new GetHomeBundlesRequest(
      new Body(limit, offset, WidgetsArgs.createDefault(resources, windowManager)), httpClient,
      converterFactory, bodyInterceptor, tokenInvalidator, sharedPreferences, widgetsUtils,
      storeCredentials, clientUniqueId, isGooglePlayServicesAvailable, partnerId, accountMature,
      filters, resources, windowManager, connectivityManager, versionCodeProvider, packageNames,
      appBundlesVisibilityManager);
}
 
Example 6
Source Project: AppServiceRestFul   Source File: NetUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取网络状态
 *
 * @param context
 * @return
 */
public static int getNetworkState(Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    // Wifi
    NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .getState();
    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
        return NETWORN_WIFI;
    }

    // 3G
    state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .getState();
    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
        return NETWORN_MOBILE;
    }
    return NETWORN_NONE;
}
 
Example 7
Source Project: o2oa   Source File: CommonUtils.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 获取当前网络类型
 *
 * @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
 */
public static int getNetworkType(Context context) {
    int netType = 0;
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo == null) {
        return netType;
    }
    int nType = networkInfo.getType();
    if (nType == ConnectivityManager.TYPE_MOBILE) {
        String extraInfo = networkInfo.getExtraInfo();
        if (!TextUtils.isEmpty(extraInfo)) {
            if (extraInfo.toLowerCase(Locale.getDefault()).equals("cmnet")) {
                netType = NETTYPE_CMNET;
            } else {
                netType = NETTYPE_CMWAP;
            }
        }
    } else if (nType == ConnectivityManager.TYPE_WIFI) {
        netType = NETTYPE_WIFI;
    }
    return netType;
}
 
Example 8
Source Project: grpc-nebula-java   Source File: AndroidChannelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
AndroidChannel(final ManagedChannel delegate, @Nullable Context context) {
  this.delegate = delegate;
  this.context = context;

  if (context != null) {
    connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
      configureNetworkMonitoring();
    } catch (SecurityException e) {
      Log.w(
          LOG_TAG,
          "Failed to configure network monitoring. Does app have ACCESS_NETWORK_STATE"
              + " permission?",
          e);
    }
  } else {
    connectivityManager = null;
  }
}
 
Example 9
private boolean isWifiOrEthernetConnection() {
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni == null) {
        // In flight mode.
        return false;
    }
    if (!ni.isConnected()) {
        // No network connection.
        return false;
    }
    switch (ni.getType()) {
        case ConnectivityManager.TYPE_WIFI:
        case ConnectivityManager.TYPE_WIMAX:
        case ConnectivityManager.TYPE_ETHERNET:
            return true;
        default:
            return false;
    }
}
 
Example 10
Source Project: SprintNBA   Source File: NetworkUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 打印当前各种网络状态
 *
 * @return boolean
 */
public static boolean printNetworkInfo(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                LogUtils.i(TAG, "NetworkInfo[" + i + "]isAvailable : " + info[i].isAvailable());
                LogUtils.i(TAG, "NetworkInfo[" + i + "]isConnected : " + info[i].isConnected());
                LogUtils.i(TAG, "NetworkInfo[" + i + "]isConnectedOrConnecting : " + info[i].isConnectedOrConnecting());
                LogUtils.i(TAG, "NetworkInfo[" + i + "]: " + info[i]);
            }
            LogUtils.i(TAG, "\n");
        } else {
            LogUtils.i(TAG, "getAllNetworkInfo is null");
        }
    }
    return false;
}
 
Example 11
@Override
public void onReceive(Context context, Intent intent) {
    if (mNetworkListener == null) {
        return;
    }

    if (intent.getAction() != null
            && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        boolean isNetworkAvailable = NetworkStateUtil.isNetworkAvailable(context);
        if (isNetworkAvailable) {
            mNetworkListener.onNetworkState(NetworkState.CONNECTED);
        } else {
            mNetworkListener.onNetworkState(NetworkState.DISCONNECTED);
        }
    }
}
 
Example 12
private boolean isMobileDataConnection() {
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni == null) {
        // In flight mode.
        return false;
    }
    if (!ni.isConnected()) {
        // No network connection.
        return false;
    }
    switch (ni.getType()) {
        case ConnectivityManager.TYPE_BLUETOOTH:
        case ConnectivityManager.TYPE_MOBILE:
        case ConnectivityManager.TYPE_MOBILE_DUN:
        case ConnectivityManager.TYPE_MOBILE_HIPRI:
            return true;
        default:
            return false;
    }
}
 
Example 13
Source Project: android-tv-launcher   Source File: NetWorkUtil.java    License: MIT License 6 votes vote down vote up
public static int getNetworkState(Context context) {
	ConnectivityManager connManager = (ConnectivityManager) context
			.getSystemService(Context.CONNECTIVITY_SERVICE);

	// Wifi
	State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
			.getState();
	if (state == State.CONNECTED || state == State.CONNECTING) {
		return STATE_WIFI;
	}

	// 3G
	state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
			.getState();
	if (state == State.CONNECTED || state == State.CONNECTING) {
		return STATE_MOBILE;
	}
	return STATE_DISCONNECT;
}
 
Example 14
Source Project: Rumble   Source File: WifiLinkLayerAdapter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void linkStart() {
    if(register)
        return;
    register = true;
    Log.d(TAG, "[+] Starting Wifi");

    wifiMan = (WifiManager) RumbleApplication.getContext().getSystemService(Context.WIFI_SERVICE);
    wifiInf = wifiMan.getConnectionInfo();
    macAddress = wifiInf.getMacAddress();

    if (WifiUtil.isWiFiApEnabled() || WifiUtil.isEnabled()) {
        linkConnected();
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    Handler handler = new Handler(getLooper());
    RumbleApplication.getContext().registerReceiver(mReceiver, filter, null, handler);
    if(!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
}
 
Example 15
Source Project: Orin   Source File: Util.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean isAllowedToDownloadMetadata(final Context context) {
    switch (PreferenceUtil.getInstance(context).autoDownloadImagesPolicy()) {
        case "always":
            return true;
        case "only_wifi":
            final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
            return netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI && netInfo.isConnectedOrConnecting();
        case "never":
        default:
            return false;
    }
}
 
Example 16
Source Project: Android-9-Development-Cookbook   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
public void getStatus(View view) {
    TextView textView = findViewById(R.id.textView);
    if (isOnline()) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        textView.setText(networkInfo.getTypeName());
    } else {
        textView.setText("Offline");
    }
}
 
Example 17
Source Project: AndroidSamples   Source File: SystemUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 检查WIFI是否连接
 */
public static boolean isWifiConnected() {
    ConnectivityManager connectivityManager = (ConnectivityManager) App.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiInfo = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    return wifiInfo != null;
}
 
Example 18
Source Project: revolution-irc   Source File: IRCService.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "Connectivity changed");
    ServerConnectionManager.getInstance(context).notifyConnectivityChanged(!intent
            .getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE));
    ServerPingScheduler.getInstance(context).onWifiStateChanged(
            ServerConnectionManager.isWifiConnected(context));
}
 
Example 19
Source Project: FireFiles   Source File: ConnectionUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isConnectedToWifi(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnected()
                && ni.getType() == ConnectivityManager.TYPE_WIFI;
    }
 
Example 20
Source Project: mapbox-events-android   Source File: ConnectivityReceiver.java    License: MIT License 5 votes vote down vote up
/**
 * Get the connectivity state as reported by the Android system
 *
 * @param context Android context
 * @return the connectivity state as reported by the Android system
 */
private static boolean getSystemConnectivity(Context context) {
  try {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) {
      return false;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork.isConnectedOrConnecting();
  } catch (Exception exception) {
    return false;
  }
}
 
Example 21
/**
 * Starts watching for changes. Must be called from a thread that has an associated {@link
 * Looper}. Listener methods are called on the caller thread.
 */
public void start() {
  Assertions.checkNotNull(Looper.myLooper());

  requirementsWereMet = requirements.checkRequirements(context);

  IntentFilter filter = new IntentFilter();
  if (requirements.getRequiredNetworkType() != Requirements.NETWORK_TYPE_NONE) {
    if (Util.SDK_INT >= 23) {
      registerNetworkCallbackV23();
    } else {
      filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    }
  }
  if (requirements.isChargingRequired()) {
    filter.addAction(Intent.ACTION_POWER_CONNECTED);
    filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
  }
  if (requirements.isIdleRequired()) {
    if (Util.SDK_INT >= 23) {
      filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
    } else {
      filter.addAction(Intent.ACTION_SCREEN_ON);
      filter.addAction(Intent.ACTION_SCREEN_OFF);
    }
  }
  receiver = new DeviceStatusChangeReceiver();
  context.registerReceiver(receiver, filter, null, new Handler());
  logd(this + " started");
}
 
Example 22
Source Project: vocefiscal-android   Source File: CommunicationUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * test if there is some connection
 * @param ctx
 * @return
 */
public static boolean verifyConnectivity(Context ctx)
{

	ConnectivityManager connectivityManager =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
	return netInfo!=null && netInfo.isConnectedOrConnecting();
}
 
Example 23
Source Project: OpenMemories-AppStore   Source File: BaseActivity.java    License: MIT License 5 votes vote down vote up
public WifiState getWifiState() {
    if (Environment.isEmulator()) {
        return WifiState.CONNECTED;
    } else {
        switch (wifiManager.getWifiState()) {
            case WifiManager.WIFI_STATE_ENABLED:
                if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                    return WifiState.CONNECTED;
                } else {
                    switch (WifiInfo.getDetailedStateOf(wifiManager.getConnectionInfo().getSupplicantState())) {
                        case SCANNING:
                            return WifiState.SCANNING;
                        case AUTHENTICATING:
                        case CONNECTING:
                        case OBTAINING_IPADDR:
                            return WifiState.CONNECTING;
                        default:
                            return WifiState.ENABLED;
                    }
                }
            case WifiManager.WIFI_STATE_ENABLING:
                return WifiState.ENABLING;
            default:
                return WifiState.DISABLED;
        }
    }
}
 
Example 24
Source Project: Emotion-Analysis-API   Source File: NetworkUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean hasInternetConnection(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if(!(networkInfo != null && networkInfo.isConnected())) {
        return false;
    } else
        return true;
}
 
Example 25
public static GetAdsRequest of(Location location, String keyword, Integer limit,
    String clientUniqueId, boolean googlePlayServicesAvailable, String oemid, boolean mature,
    OkHttpClient httpClient, Converter.Factory converterFactory, String q,
    SharedPreferences sharedPreferences, ConnectivityManager connectivityManager,
    Resources resources, AdsApplicationVersionCodeProvider versionCodeProvider) {
  GetAdsRequest adsRequest =
      new GetAdsRequest(clientUniqueId, googlePlayServicesAvailable, oemid, mature,
          converterFactory, httpClient, q, sharedPreferences, connectivityManager, resources,
          versionCodeProvider);
  adsRequest.setLocation(location);
  adsRequest.setKeyword(keyword);
  adsRequest.setLimit(limit);
  return adsRequest;
}
 
Example 26
Source Project: ReadMark   Source File: NetworkUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否是wifi连接
 */
public static boolean isWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm == null)
        return false;
    return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

}
 
Example 27
Source Project: osmdroid   Source File: NetworkAvailabliltyCheck.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean getWiFiNetworkAvailable() {
	if (!mHasNetworkStatePermission) {
		// if we're unable to check network state, assume we have a network
		return true;
	}
	final NetworkInfo wifi = mConnectionManager
			.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	return wifi != null && wifi.isConnected();
}
 
Example 28
Source Project: android_9.0.0_r45   Source File: DataConnectionStats.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
        updateSimState(intent);
        notePhoneDataConnectionState();
    } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
            action.equals(ConnectivityManager.INET_CONDITION_ACTION)) {
        notePhoneDataConnectionState();
   }
}
 
Example 29
Source Project: letv   Source File: NetworkUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isNetworkConnected(Context context) {
    boolean isConnected = false;
    try {
        isConnected = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo().isConnectedOrConnecting();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return isConnected;
}
 
Example 30
Source Project: sketch   Source File: MobileDataPauseDownloadController.java    License: Apache License 2.0 5 votes vote down vote up
private void register() {
    try {
        context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
}