android.net.ConnectivityManager Java Examples

The following examples show how to use android.net.ConnectivityManager. 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: Network.java    From MiBandDecompiled with 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 #2
Source File: ConnectionsManager.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
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 #3
Source File: NetWorkUtil.java    From android-tv-launcher with 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 #4
Source File: WifiLinkLayerAdapter.java    From Rumble with 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 #5
Source File: RunConditionMonitor.java    From syncthing-android with Mozilla Public License 2.0 6 votes vote down vote up
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 #6
Source File: ApplicationLoader.java    From Telegram with 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 #7
Source File: GetHomeBundlesRequest.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: NetworkBroadcastReceiver.java    From AutoRefreshNetworkConnection with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: NetUtil.java    From AppServiceRestFul with 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 #10
Source File: CommonUtils.java    From o2oa with 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 #11
Source File: NetworkUtils.java    From SprintNBA with 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 #12
Source File: RunConditionMonitor.java    From syncthing-android with Mozilla Public License 2.0 6 votes vote down vote up
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 #13
Source File: AndroidChannelBuilder.java    From grpc-nebula-java with 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 #14
Source File: NetworkUtil.java    From AndroidBasicProject with MIT License 5 votes vote down vote up
/**
 * 网络是否可用
 */
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager mgr =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] info = mgr.getAllNetworkInfo();
    if (info != null) {
        for (int i = 0; i < info.length; i++) {
            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
    }
    return false;
}
 
Example #15
Source File: NoInternetDialog.java    From NoInternetDialog with Apache License 2.0 5 votes vote down vote up
private void initReceivers(Context context) {
    wifiReceiver = new WifiReceiver();
    context.registerReceiver(wifiReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    networkStatusReceiver = new NetworkStatusReceiver();
    context.registerReceiver(networkStatusReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    wifiReceiver.setConnectionListener(this);
    networkStatusReceiver.setConnectionCallback(this);
}
 
Example #16
Source File: DeviceInfo.java    From deviceinfo with Apache License 2.0 5 votes vote down vote up
/**
 * Check connection type for wifi
 *
 * @return true, if current connection is WiFi
 */
public boolean isWifiConnection() {
   try {
      ConnectivityManager manager = (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo ni = manager.getActiveNetworkInfo();
      return ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI;
   } catch (Throwable t) {
      // https://fabric.io/eyeem/android/apps/com.baseapp.eyeem/issues/577f965affcdc0425064069f
      return false;
   }
}
 
Example #17
Source File: NetWorkUtil.java    From Toutiao with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否有网络连接
 */
public static boolean isNetworkConnected(Context context) {
    if (context != null) {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //判断NetworkInfo对象是否为空
        return null != networkInfo && networkInfo.isAvailable();
    }
    return false;
}
 
Example #18
Source File: NetworkMonitorAutoDetect.java    From webrtc_android with MIT License 5 votes vote down vote up
/**
 * Constructs a NetworkMonitorAutoDetect. Should only be called on UI thread.
 */
@SuppressLint("NewApi")
public NetworkMonitorAutoDetect(Observer observer, Context context) {
  this.observer = observer;
  this.context = context;
  connectivityManagerDelegate = new ConnectivityManagerDelegate(context);
  wifiManagerDelegate = new WifiManagerDelegate(context);

  final NetworkState networkState = connectivityManagerDelegate.getNetworkState();
  connectionType = getConnectionType(networkState);
  wifiSSID = getWifiSSID(networkState);
  intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

  if (PeerConnectionFactory.fieldTrialsFindFullName("IncludeWifiDirect").equals("Enabled")) {
    wifiDirectManagerDelegate = new WifiDirectManagerDelegate(observer, context);
  }

  registerReceiver();
  if (connectivityManagerDelegate.supportNetworkCallback()) {
    // On Android 6.0.0, the WRITE_SETTINGS permission is necessary for
    // requestNetwork, so it will fail. This was fixed in Android 6.0.1.
    NetworkCallback tempNetworkCallback = new NetworkCallback();
    try {
      connectivityManagerDelegate.requestMobileNetwork(tempNetworkCallback);
    } catch (java.lang.SecurityException e) {
      Logging.w(TAG, "Unable to obtain permission to request a cellular network.");
      tempNetworkCallback = null;
    }
    mobileNetworkCallback = tempNetworkCallback;
    allNetworkCallback = new SimpleNetworkCallback();
    connectivityManagerDelegate.registerNetworkCallback(allNetworkCallback);
  } else {
    mobileNetworkCallback = null;
    allNetworkCallback = null;
  }
}
 
Example #19
Source File: VMNetwork.java    From VMLibrary with Apache License 2.0 5 votes vote down vote up
/**
 * 网络已经连接情况下,去判断是 WIFI 还是 GPRS
 * 可以根据返回情况做一些自己的逻辑调用
 */
private boolean isGPRSNetwork() {
    State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
    if (gprs == State.CONNECTED || gprs == State.CONNECTING) {
        return true;
    }
    return false;
}
 
Example #20
Source File: FadeInNetworkImageView.java    From QuickLyric with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
@Override
public void setImageUrl(String url, ImageLoader imageLoader) {
    mShowLocal = TextUtils.isEmpty(url);
    if (mDiskCache.get(url) == null && !OnlineAccessVerifier.check(getContext())) {
        this.setImageBitmap(null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final ConnectivityManager cm = (ConnectivityManager)
                    getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    new CoverArtLoader((MainActivity) FadeInNetworkImageView.this.getActivity()).execute(mLyrics);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && networkCallback != null)
                        try {
                            cm.unregisterNetworkCallback(networkCallback);
                        } catch (IllegalArgumentException ignored) {
                        }
                }
            };
            NetworkRequest request = new NetworkRequest.Builder()
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
            cm.registerNetworkCallback(request, networkCallback);
        }
        defaultShown = true;
    } else {
        super.setImageUrl(url, imageLoader);
        if (!TextUtils.isEmpty(url))
            defaultShown = false;
    }
}
 
Example #21
Source File: Utility.java    From Advanced_Android_Development with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the network is available or about to become available.
 *
 * @param c Context used to get the ConnectivityManager
 * @return true if the network is available
 */
static public boolean isNetworkAvailable(Context c) {
    ConnectivityManager cm =
            (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
}
 
Example #22
Source File: Util.java    From SocietyPoisonerTrojan with GNU General Public License v3.0 5 votes vote down vote up
public static String getCurrentSSID (Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        return connectionInfo.getSSID();
    }

    return null;
}
 
Example #23
Source File: RunConditionMonitor.java    From syncthing-android with Mozilla Public License 2.0 5 votes vote down vote up
public RunConditionMonitor(Context context, OnRunConditionChangedListener listener) {
    Log.v(TAG, "Created new instance");
    ((SyncthingApp) context.getApplicationContext()).component().inject(this);
    mContext = context;
    mOnRunConditionChangedListener = listener;

    /**
     * Register broadcast receivers.
     */
    // NetworkReceiver
    ReceiverManager.registerReceiver(mContext, new NetworkReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    // BatteryReceiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_POWER_CONNECTED);
    filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    ReceiverManager.registerReceiver(mContext, new BatteryReceiver(), filter);

    // PowerSaveModeChangedReceiver
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ReceiverManager.registerReceiver(mContext,
                new PowerSaveModeChangedReceiver(),
                new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED));
    }

    // SyncStatusObserver to monitor android's "AutoSync" quick toggle.
    mSyncStatusObserverHandle = ContentResolver.addStatusChangeListener(
            ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver);

    // Initially determine if syncthing should run under current circumstances.
    updateShouldRunDecision();
}
 
Example #24
Source File: NetworkUtils.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 5 votes vote down vote up
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean isNetworkAvailable(@NonNull Context context) {

    boolean result = false;
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);     // Use getApplicationContext to solve a bug on Android M: https://stackoverflow.com/questions/41431409/connectivitymanager-leaking-not-sure-how-to-resolve
    if (connectivityManager != null) {
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            result = activeNetworkInfo.isConnected();
        }
    }

    return result;
}
 
Example #25
Source File: RequirementsWatcher.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #26
Source File: SnippetsLauncher.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@CalledByNative
public boolean isOnUnmeteredConnection() {
    Context context = ContextUtils.getApplicationContext();
    ConnectivityManager manager =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return !manager.isActiveNetworkMetered();
}
 
Example #27
Source File: DeviceStateReceiver.java    From EasyVPN-Free with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);


    if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
        networkStateChange(context);
    } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
        boolean screenOffPause = prefs.getBoolean("screenoff", false);

        if (screenOffPause) {
            if (ProfileManager.getLastConnectedVpn() != null && !ProfileManager.getLastConnectedVpn().mPersistTun)
                VpnStatus.logError(R.string.screen_nopersistenttun);

            screen = connectState.PENDINGDISCONNECT;
            fillTrafficData();
            if (network == connectState.DISCONNECTED || userpause == connectState.DISCONNECTED)
                screen = connectState.DISCONNECTED;
        }
    } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
        // Network was disabled because screen off
        boolean connected = shouldBeConnected();
        screen = connectState.SHOULDBECONNECTED;

        /* We should connect now, cancel any outstanding disconnect timer */
        mDisconnectHandler.removeCallbacks(mDelayDisconnectRunnable);
        /* should be connected has changed because the screen is on now, connect the VPN */
        if (shouldBeConnected() != connected)
            mManagement.resume();
        else if (!shouldBeConnected())
            /*Update the reason why we are still paused */
            mManagement.pause(getPauseReason());

    }
}
 
Example #28
Source File: ConnectivityChangeReceiver.java    From android-migrate-to-jobs with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent == null) {
        return;
    }

    String action = intent.getAction();
    if (TextUtils.isEmpty(action) || !ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
        return;
    }

    injectOnce(context);
    bus.postRetryDownloads(itemStore);
}
 
Example #29
Source File: Util.java    From Orin with 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 #30
Source File: NetworkUtil.java    From RxZhihuDaily with MIT License 5 votes vote down vote up
public static String getNetType() {
    int type = NetworkUtil.getNetType(BaseApplication.get());
    String netType;
    if (type < 0)
        netType = "fail";
    else if (type == ConnectivityManager.TYPE_WIFI) {
        netType = "wifi";
    } else if (type == ConnectivityManager.TYPE_MOBILE) {
        netType = "wwan";
    } else {
        netType = "edge";
    }
    return netType;
}