Java Code Examples for android.net.NetworkInfo

The following are top voted examples for showing how to use android.net.NetworkInfo. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: eazycore   File: NetWorkUtils.java   Source Code and License 7 votes vote down vote up
/**
 * Get network type
 * 
 * @param context
 * @return
 */
public static int getNetworkType(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager)context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager == null ? null : connectivityManager.getActiveNetworkInfo();
    return networkInfo == null ? -1 : networkInfo.getType();
}
 
Example 2
Project: LibVNCAndroid   File: ActivityTabs.java   Source Code and License 7 votes vote down vote up
/**
 * @brief Checks the connectivity type of the terminal
 * @return True if the connectivity type is Wifi, false in another case.
 * @details Checks the connectivity type of the terminal
 */
//devuelve true si es conexion wifi, false en caso contrario
private boolean isWifiConnectivityType(){
	ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo info = connectivityManager.getActiveNetworkInfo();
       
       String connectionType = info.getTypeName();
       
       if (connectionType.equalsIgnoreCase("wifi")){
       	return true;
       }
       else{
       	//3g u otro tipo
       	return false;
       }
       	
}
 
Example 3
Project: GitHub   File: ConnectivityReceiver.java   Source Code and License 7 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	final String action = intent.getAction();

	if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
		Log.w(TAG, "onReceived() called: " + intent);
		return;
	}

	boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
	boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

	Log.d(TAG, "onReceived() called; noConnectivity? " + noConnectivity + "; isFailover? " + isFailover);

	if (noConnectivity && !isFailover && mIsConnected) {
		mIsConnected = false;
		mTerminalManager.onConnectivityLost();
	} else if (!mIsConnected) {
		NetworkInfo info = (NetworkInfo) intent.getExtras()
				.get(ConnectivityManager.EXTRA_NETWORK_INFO);

		if (mIsConnected = (info.getState() == State.CONNECTED)) {
			mTerminalManager.onConnectivityRestored();
		}
	}
}
 
Example 4
Project: browser   File: MainApp.java   Source Code and License 6 votes vote down vote up
public boolean isNetworkAvailable() {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
	}
 
Example 5
Project: JobSchedulerCompat   File: DeviceTestUtils.java   Source Code and License 6 votes vote down vote up
public static void setNetworkInfo(Context context, boolean isConnected, boolean isRoaming, boolean isWifi) {
    ShadowConnectivityManager manager =
            shadowOf((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    NetworkInfo.DetailedState detailedState =
            isConnected ? NetworkInfo.DetailedState.CONNECTED : NetworkInfo.DetailedState.DISCONNECTED;
    int type = isConnected ? (isWifi ? ConnectivityManager.TYPE_WIFI : ConnectivityManager.TYPE_MOBILE) : -1;
    NetworkInfo networkInfo =
            ShadowNetworkInfo.newInstance(detailedState, type, 0, isConnected, isConnected, isRoaming);
    manager.setActiveNetworkInfo(networkInfo);
}
 
Example 6
Project: airgram   File: ConnectionsManager.java   Source Code and License 6 votes vote down vote up
public static boolean isRoaming() {
    try {
        ConnectivityManager cm = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null) {
            return netInfo.isRoaming();
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    return false;
}
 
Example 7
Project: OCast-Java   File: WifiMonitor.java   Source Code and License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo networkInfo =
                intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if(networkInfo.isConnected()) {
            if(!mIsConnected) {
                Log.d(TAG, "Wifi is connected: " + String.valueOf(networkInfo));
                mListener.onConnectionStateChanged(true);
                mIsConnected = true;
            }
        } else {
            if(mIsConnected) {
                Log.d(TAG, "Wifi is disconnected: " + String.valueOf(networkInfo));
                mIsConnected = false;
                mListener.onConnectionStateChanged(false);
            }
        }
    }
}
 
Example 8
Project: LoriApp   File: AppModule.java   Source Code and License 6 votes vote down vote up
@Singleton
@Provides
NetworkChecker networkChecker(LoriApp app) {
    return () -> {
        ConnectivityManager internetManager = (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting();
    };
}
 
Example 9
Project: Ency   File: AppNetWorkUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 获取当前网络状态类型
 *
 * @param context
 * @return
 */
public static int getNetworkType(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    int type = TYPE_NO;
    if (info != null && info.isAvailable()) {
        //获取网络类型
        int netWorkType = info.getType();
        if (netWorkType == ConnectivityManager.TYPE_WIFI) {
            type = TYPE_WIFI;
        } else if (netWorkType == ConnectivityManager.TYPE_MOBILE) {
            type = TYPE_MOBILE;
        } else {
            type = TYPE_UNKNOWN;
        }
    }
    return type;
}
 
Example 10
Project: SyncMarket   File: SyncMarket.java   Source Code and License 6 votes vote down vote up
public static boolean isNetworkAvailable() {
    boolean status = false;
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null
            && netInfo.getState() == NetworkInfo.State.CONNECTED) {
        status = true;
    } else {
        netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null
                && netInfo.getState() == NetworkInfo.State.CONNECTED)
            status = true;
    }
    return status;
}
 
Example 11
Project: MegviiLicMgr-Android-SDK   File: NetWorkHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 获取网络连接状态
 */
public static int getNetworkType(Context context) {
    // NetworkInfo 有以下方法
    // getDetailedState():获取详细状态。
    // getExtraInfo():获取附加信息(3gnet/3gwap/uninet/uniwap/cmnet/cmwap/ctnet/ctwap)
    // getReason():获取连接失败的原因。
    // getType():获取网络类型(一般为移动或Wi-Fi)。
    // getTypeName():获取网络类型名称(一般取值“WIFI”或“MOBILE”)。
    // isAvailable():判断该网络是否可用。
    // isConnected():判断是否已经连接。
    // isConnectedOrConnecting():判断是否已经连接或正在连接。
    // isFailover():判断是否连接失败。
    // isRoaming():判断是否漫游

    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
    if (networkInfo != null) {
        int type = networkInfo.getType();
        State state = networkInfo.getState();

        if (type == ConnectivityManager.TYPE_WIFI
                && state == State.CONNECTED) {
            // wifi连接通畅
            return NETWORK_CONNETED_WIFI;
        } else if (type == ConnectivityManager.TYPE_MOBILE
                && state == State.CONNECTED) {
            return NETWORK_CONNETED_GPRS;
        }
    }
    return NETWORK_DISCONNETED;
}
 
Example 12
Project: letv   File: NetworkUtils.java   Source Code and License 6 votes vote down vote up
public static int getNetworkType() {
    NetworkInfo networkInfo = ((ConnectivityManager) BaseApplication.getInstance().getSystemService("connectivity")).getActiveNetworkInfo();
    if (networkInfo == null || !networkInfo.isAvailable()) {
        return 0;
    }
    if (1 == networkInfo.getType()) {
        return 1;
    }
    switch (((TelephonyManager) BaseApplication.getInstance().getSystemService("phone")).getNetworkType()) {
        case 1:
        case 2:
        case 4:
            return 2;
        case 13:
            return 3;
        default:
            return 3;
    }
}
 
Example 13
Project: Moodr   File: StrangerProfile.java   Source Code and License 6 votes vote down vote up
/**
 * Checks if there is already a pending request for the user.
 *
 * @param name of user pending
 * @return Boolean value. Whether if there is a pending request for the user.
 * @throws Exception
 */
private boolean checkPending(String name) { // change to more specific exception later.
    // Check if app is connected to a network.
    ConnectivityManager cm = (ConnectivityManager) getActivity().getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null == activeNetwork) {
        Toast.makeText(getActivity(), "You are offline.", Toast.LENGTH_SHORT).show();
    } else {
        ElasticSearchUserController.GetUserTask getUserTask =
                new ElasticSearchUserController.GetUserTask();
        getUserTask.execute(name.toLowerCase());
        try {
            User user2 = getUserTask.get().get(0); // get first user from result
            String currentUsername = CurrentUserSingleton.getInstance().getUser().getName();
            return user2.getPending().contains(currentUsername);
        } catch (Exception e) {
            Log.d("Error", "Unable to get user from elastic search");
        }
    }
    return false;
}
 
Example 14
Project: Linphone4Android   File: LinphoneManager.java   Source Code and License 6 votes vote down vote up
private boolean isTunnelNeeded(NetworkInfo info) {
	if (info == null) {
		Log.i("No connectivity: tunnel should be disabled");
		return false;
	}

	String pref = mPrefs.getTunnelMode();

	if (getString(R.string.tunnel_mode_entry_value_always).equals(pref)) {
		return true;
	}

	if (info.getType() != ConnectivityManager.TYPE_WIFI
			&& getString(R.string.tunnel_mode_entry_value_3G_only).equals(pref)) {
		Log.i("need tunnel: 'no wifi' connection");
		return true;
	}

	return false;
}
 
Example 15
Project: Swap   File: SpecialFragment.java   Source Code and License 6 votes vote down vote up
private void loadnet() {


        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
        //获取系统的连接服务。
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        //获取网络的连接情况。
        if (networkInfo != null && networkInfo.isAvailable()) {
          /*  if (networkInfo.getType()==connectivityManager.TYPE_WIFI){
                Toast.makeText(A.this,"网络已启动啦(WIFI)",Toast.LENGTH_SHORT).show();
            }else if (networkInfo.getType()==connectivityManager.TYPE_MOBILE) {
                Toast.makeText(A.this,"网络已启动啦(3G)",Toast.LENGTH_SHORT).show();

            }*/
            loadingLayout.setStatus(LoadingLayout.Success);//加载成功


        } else {
            loadingLayout.setStatus(LoadingLayout.Loading);
        }

    }
 
Example 16
Project: treasure   File: Network.java   Source Code and License 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 in = connectivity.getActiveNetworkInfo();
        Log.i(TAG, "-------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-------------");
        Log.i(TAG, "getActiveNetworkInfo: " + in);
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                // if (info[i].getType() == ConnectivityManager.TYPE_WIFI) {
                Log.i(TAG, "NetworkInfo[" + i + "]isAvailable : " + info[i].isAvailable());
                Log.i(TAG, "NetworkInfo[" + i + "]isConnected : " + info[i].isConnected());
                Log.i(TAG, "NetworkInfo[" + i + "]isConnectedOrConnecting : " + info[i].isConnectedOrConnecting());
                Log.i(TAG, "NetworkInfo[" + i + "]: " + info[i]);
                // }
            }
            Log.i(TAG, "\n");
        } else {
            Log.i(TAG, "getAllNetworkInfo is null");
        }
    }
    return false;
}
 
Example 17
Project: decoy   File: NetworkUtil.java   Source Code and License 6 votes vote down vote up
public static String getNetworkInfo(Context context) {
	String info = "";
	ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	if (connectivity != null) {
		NetworkInfo activeNetInfo = connectivity.getActiveNetworkInfo();
		if (activeNetInfo != null) {
			if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				info = activeNetInfo.getTypeName();
			} else {
				StringBuilder sb = new StringBuilder();
				TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
				sb.append(activeNetInfo.getTypeName());
				sb.append(" [");
				if (tm != null) {
					// Result may be unreliable on CDMA networks
					sb.append(tm.getNetworkOperatorName());
					sb.append("#");
				}
				sb.append(activeNetInfo.getSubtypeName());
				sb.append("]");
				info = sb.toString();
			}
		}
	}
	return info;
}
 
Example 18
Project: siiMobilityAppKit   File: NetworkManager.java   Source Code and License 6 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("getConnectionInfo")) {
        this.connectionCallbackContext = callbackContext;
        NetworkInfo info = sockMan.getActiveNetworkInfo();
        String connectionType = "";
        try {
            connectionType = this.getConnectionInfo(info).get("type").toString();
        } catch (JSONException e) {
            LOG.d(LOG_TAG, e.getLocalizedMessage());
        }

        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }
    return false;
}
 
Example 19
Project: GitHub   File: NetUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 判断网络是否连接
 */
public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);

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

    NetworkInfo info = cm.getActiveNetworkInfo();
    if (null != info && info.isConnected()) {
        if (info.getState() == NetworkInfo.State.CONNECTED) {
            return true;
        }
    }
    return false;
}
 
Example 20
Project: DailyStudy   File: Utility.java   Source Code and License 6 votes vote down vote up
/**
 * 检测网络是否可用
 *
 * @param context context
 * @return 网络是否可用
 */
public static boolean isNetworkConnected(Context context) {
    boolean flag = false;
    if (null == context) {
        return false;
    }
    try {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        }
        NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
        flag = networkInfo != null && networkInfo.isAvailable();
    } catch (Exception e) {
        Log.v(TAG, e.toString());
        return false;
    }
    return flag;
}
 
Example 21
Project: Rx_java2_soussidev   File: RxConnectionfragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    networkDisposable = ReactiveNetwork.observeNetworkConnectivity(getActivity())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(connectivity -> {
                Log.d(TAG, connectivity.toString());
                final NetworkInfo.State state = connectivity.getState();
                final String name = connectivity.getTypeName();
                tvConnectivityStatus.setText(String.format("state: %s, typeName: %s", state, name));
            });

    internetDisposable = ReactiveNetwork.observeInternetConnectivity()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(isConnected -> tvInternetStatus.setText(isConnected.toString()));
}
 
Example 22
Project: MegviiLicMgr-Android-SDK   File: NetWorkHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 网络连接是否通畅
 */
public static int isDataConnection(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    String Mode_airpln = Settings.System.getString(
            context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
    // Log.i("CommonHelper", "isDataConnection >> 飞行模式 = "+Mode_airpln);
    if (Mode_airpln != null && Mode_airpln.equalsIgnoreCase("1")) {
        // Log.i("CommonHelper", "isDataConnection >> 飞行模式:开");
        return -1;
    }

    if (networkInfo != null && networkInfo.isConnected()) {
        // Log.i("CommonHelper", "isDataConnection >> 网络状态:已连接");
        return 1;
    } else {
        // Log.i("CommonHelper", "isDataConnection >> 网络状态:未连接");
        return 0;
    }
}
 
Example 23
Project: android-project-gallery   File: DaemonService.java   Source Code and License 6 votes vote down vote up
public boolean isNetworkAvailable()
{
	Context context = getApplicationContext();
	ConnectivityManager connect = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	if (connect == null)
	{
		return false;
	}
	else
	{
		// get all network info
		NetworkInfo[] info = connect.getAllNetworkInfo();
		if (info != null)
		{
			for (int i = 0; i < info.length; i++)
			{
				if (info[i].getState() == NetworkInfo.State.CONNECTED)
				{
					return true;
				}
			}
		}
	}

	return false;
}
 
Example 24
Project: browser   File: MainApp.java   Source Code and License 5 votes vote down vote up
public  boolean hasNetwork() {
    if(context==null){
        return  false;
    }
    android.net.ConnectivityManager cManager = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo info = cManager.getActiveNetworkInfo();
    if (info != null && info.isAvailable()) {
        return true;
    } else {
        return false;
    }
}
 
Example 25
Project: robird-reborn   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnectedOrConnecting()
            && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
 
Example 26
Project: RLibrary   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
public static NetworkType getNetworkType(NetworkInfo info) {
    NetworkType netType = NetworkType.NETWORK_NO;
    if (info != null && info.isAvailable()) {

        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            netType = NetworkType.NETWORK_WIFI;
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            switch (info.getSubtype()) {

                case NETWORK_TYPE_GSM:
                case TelephonyManager.NETWORK_TYPE_GPRS:
                case TelephonyManager.NETWORK_TYPE_CDMA:
                case TelephonyManager.NETWORK_TYPE_EDGE:
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                case TelephonyManager.NETWORK_TYPE_IDEN:
                    netType = NetworkType.NETWORK_2G;
                    break;

                case NETWORK_TYPE_TD_SCDMA:
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                case TelephonyManager.NETWORK_TYPE_UMTS:
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                case TelephonyManager.NETWORK_TYPE_HSPA:
                case TelephonyManager.NETWORK_TYPE_EVDO_B:
                case TelephonyManager.NETWORK_TYPE_EHRPD:
                case TelephonyManager.NETWORK_TYPE_HSPAP:
                    netType = NetworkType.NETWORK_3G;
                    break;

                case NETWORK_TYPE_IWLAN:
                case TelephonyManager.NETWORK_TYPE_LTE:
                    netType = NetworkType.NETWORK_4G;
                    break;
                default:

                    String subtypeName = info.getSubtypeName();
                    if (subtypeName.equalsIgnoreCase("TD-SCDMA")
                            || subtypeName.equalsIgnoreCase("WCDMA")
                            || subtypeName.equalsIgnoreCase("CDMA2000")) {
                        netType = NetworkType.NETWORK_3G;
                    } else {
                        netType = NetworkType.NETWORK_UNKNOWN;
                    }
                    break;
            }
        } else {
            netType = NetworkType.NETWORK_UNKNOWN;
        }
    }
    return netType;
}
 
Example 27
Project: android-lite-utils   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 判断网络是否连接
 *
 * @param context
 * @return
 */
public boolean isConnected(Context context) {
    ConnectivityManager connectivity = getConnectivityManager(context);
    if (null != connectivity) {
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (null != info && info.isConnected()) {
            if (info.getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
    }
    return false;
}
 
Example 28
Project: RetrofitSample   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 检查是否是移动网络
 */
public static boolean isMobile(Context context) {
    NetworkInfo info = getNetworkInfo(context);
    if (info != null) {
        if (info.getType() == ConnectivityManager.TYPE_MOBILE)
            return true;
    }
    return false;
}
 
Example 29
Project: MVP   File: NetworkUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 检查是否连接网络
 * @param context
 * @return
 */
public static boolean  checkedNetWork(Context context){
	// 1.获得连接设备管理器
	ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	if(cm == null) return false;
	/**
	 * 获取网络连接对象
	 */
	NetworkInfo networkInfo = cm.getActiveNetworkInfo();
	
	if(networkInfo == null || !networkInfo.isAvailable()){
		return false;
	}
	return true;
}
 
Example 30
Project: KTools   File: NetworkUtils.java   Source Code and License 5 votes vote down vote up
public static String getNetWorkType() {
    NetworkInfo networkInfo = sConnectivityManager.getActiveNetworkInfo();
    NetworkInfo mobileInfo = sConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    NetworkInfo wifiInfo = sConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo == null || !networkInfo.isAvailable()) {
        return NETWORK_TYPE_OFFLINE;
    } else if (wifiInfo != null && wifiInfo.isAvailable()) {
        return NETWORK_TYPE_WIFI;
    } else if (mobileInfo != null && mobileInfo.isAvailable()) {
        return NETWORK_TYPE_MOBILE;
    } else {
        return NETWORK_TYPE_OTHER;
    }
}
 
Example 31
Project: Moodr   File: ViewMyMoodActivity.java   Source Code and License 5 votes vote down vote up
/**
 * deletes the current mood the user is viewing.
 */
private void deleteMood() {

    // Check if app is connected to a network.
    ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    CurrentUserSingleton.getInstance().getMyMoodList().delete(mood);
    if (null == activeNetwork) {
        Toast.makeText(getApplicationContext(), "This mood will be deleted in database once Moodr has internet connection.", Toast.LENGTH_SHORT).show();
        CurrentUserSingleton.getInstance().getMyOfflineActions().addAction(3, mood);
    } else {
        //update on server
        ElasticSearchMoodController.DeleteMoodTask deleteMoodTask = new ElasticSearchMoodController.DeleteMoodTask();
        deleteMoodTask.execute(mood);
    }
    new SaveSingleton(getApplicationContext()).SaveSingletons(); // save singleton to disk.
}
 
Example 32
Project: wallpaperboard   File: Preferences.java   Source Code and License 5 votes vote down vote up
public boolean isConnectedToNetwork() {
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                mPreferences.get().mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    } catch (Exception e) {
        return false;
    }
}
 
Example 33
Project: skeletoid   File: ConnectivityReceiver.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = null;
    if (connMgr != null) {
        networkInfo = connMgr.getActiveNetworkInfo();
    }

    boolean isReachable = networkInfo != null && networkInfo.isConnected();

    // This variable can change from true to false in background via validateInternetStatus()
    // Use case: You have connection, but no internet
    isInternetAvailable = false;
    isInWiFi = networkInfo != null ? networkInfo.getType() == ConnectivityManager.TYPE_WIFI
            : false;

    if (mPreviousReachableState == null || mPreviousReachableState != isReachable) {

        mPreviousReachableState = isReachable;

        LOG.d(LOG_TAG, "Connectivity changed " + isReachable);
    }

    if (isReachable) {
        validateInternetStatus(3);
    } else {
        notifyConnectionStatus();
    }


}
 
Example 34
Project: RLibrary   File: FileDownloadUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isNetworkNotOnWifiType() {
    final ConnectivityManager manager = (ConnectivityManager) FileDownloadHelper.getAppContext().
            getSystemService(Context.CONNECTIVITY_SERVICE);

    if (manager == null) {
        FileDownloadLog.w(FileDownloadUtils.class, "failed to get connectivity manager!");
        return true;
    }

    final NetworkInfo info = manager.getActiveNetworkInfo();

    return info == null || info.getType() != ConnectivityManager.TYPE_WIFI;
}
 
Example 35
Project: AIMSICDL   File: Helpers.java   Source Code and License 5 votes vote down vote up
/**
 * Checks if Network connectivity is available to download OpenCellID data
 * Requires:        android:name="android.permission.ACCESS_NETWORK_STATE"
 */
public static Boolean isNetAvailable(Context context) {
    try {
        ConnectivityManager cM = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiInfo =   cM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobileInfo = cM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (wifiInfo != null && mobileInfo != null) {
            return wifiInfo.isConnected() || mobileInfo.isConnected();
        }
    } catch (Exception e) {
       Log.e(TAG, mTAG + e.getMessage(), e);
    }
    return false;
}
 
Example 36
Project: LeagueOfAndroid   File: Utils.java   Source Code and License 5 votes vote down vote up
public static boolean isConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();

    return activeNetworkInfo != null;
}
 
Example 37
Project: PlayAndroid   File: NetworkUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取当前网络连接的类型信息
 * 原生
 */
public static int getConnectedType() {
    //获取NetworkInfo对象
    NetworkInfo networkInfo = getConnectivityManager().getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isAvailable())
        //返回NetworkInfo的类型
        return networkInfo.getType();
    else
        return -1;
}
 
Example 38
Project: AndroidConnectivity   File: NetworkInfoToConnectionStatusAdapter.java   Source Code and License 5 votes vote down vote up
public boolean isConnected(NetworkInfo networkInfo) {
    if (null != networkInfo) {
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
    }
    return false;
}
 
Example 39
Project: letv   File: bt.java   Source Code and License 5 votes vote down vote up
public static boolean l(Context context) {
    try {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            return activeNetworkInfo.isConnectedOrConnecting();
        }
        return false;
    } catch (Exception e) {
        return true;
    }
}
 
Example 40
Project: letv   File: l.java   Source Code and License 5 votes vote down vote up
public static boolean c() {
    try {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) a().a.getSystemService("connectivity")).getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.getType() == 1) {
            return true;
        }
    } catch (Exception e) {
    }
    return false;
}