Android App的开发大多数情况下都要与网络进行连接,那如何判断网络是否连接,处于何种连接呢?下面是关于连接写的一个方法,可以根据需求做相应的修改:
private String connection(Context context) {//判断联网,一定要记得写权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> String connectInfo = "网络未连接"; ConnectivityManager connect = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connect.getActiveNetworkInfo(); if(info != null && info.isConnected()){ //if(info.isAvailable()){//此判断在使用时会有异常,需要处理 connectInfo = "网络已经连接,"; //GPS是否打开 if(isGpsEnabled(this)){ connectInfo += "GPS已经开启"; }else { connectInfo += "GPS未开启"; } //WiFi是否打开 if(isWifiEnabled(this,connect)){ connectInfo += "WIFI开启"; }else { connectInfo += "WIFI未开启"; } int netType = info.getType(); if(netType == ConnectivityManager.TYPE_WIFI){ connectInfo += "\n当前使用WIFI"; }else if(netType == ConnectivityManager.TYPE_MOBILE){ connectInfo += "\n当前使用移动连接"; }else { connectInfo += "\n当前使用连接是:"+netType; } } return connectInfo;} //判断GPS是否打开public static boolean isGpsEnabled(Context context) { LocationManager lm = ((LocationManager) context .getSystemService(Context.LOCATION_SERVICE)); List<String> accessibleProviders = lm.getProviders(true); return accessibleProviders != null && accessibleProviders.size() > 0;}//判断WIFI是否打开public static boolean isWifiEnabled(Context context,ConnectivityManager mgrConn) { TelephonyManager mgrTel = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return ((mgrConn.getActiveNetworkInfo() != null && mgrConn .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);}
时间: 2024-10-09 02:11:46