比较简单的检测网络:
1 /** 2 * 检查网络是否连接 3 * @param context 4 * @return 5 */ 6 public boolean isNetworkConnected(Context context) { 7 if (context != null) { 8 ConnectivityManager mConnectivityManager = (ConnectivityManager) context 9 .getSystemService(Context.CONNECTIVITY_SERVICE); 10 // 获取有效的网络信息 11 NetworkInfo mNetworkInfo = mConnectivityManager 12 .getActiveNetworkInfo(); 13 if (mNetworkInfo != null) { 14 // 返回网络是否可用 15 return mNetworkInfo.isAvailable(); 16 } 17 } 18 return false; 19 }
用广播的方式检测网络连接状态,以及接入点的名称:
1 /** 2 * 网络连接广播接收 3 * @author Administrator 4 * 5 */ 6 private class CheckNetStateRecevicer extends BroadcastReceiver { 7 8 @Override 9 public void onReceive(Context context, Intent intent) { 10 // TODO Auto-generated method stub 11 if (intent.getAction().equals( 12 ConnectivityManager.CONNECTIVITY_ACTION)) { 13 Log.i("Info", "网络状态已经改变"); 14 cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // 获得网络连接服务 15 networkInfo = cm.getActiveNetworkInfo(); // 获得可用的网络信息 16 17 if (networkInfo != null 18 && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { 19 String netId = networkInfo.getExtraInfo(); // 获得手机接入点的网络模式 20 Toast.makeText(context, "网络已连接至" + netId, Toast.LENGTH_SHORT) 21 .show(); 22 } else if (networkInfo != null 23 && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { 24 WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); 25 String ssid = wm.getConnectionInfo().getSSID().toString(); // 获得WiFi接入点的名称 26 Toast.makeText(context, "网络已连接至" + ssid, Toast.LENGTH_SHORT) 27 .show(); 28 } else { 29 Toast.makeText(context, "网络出现异常", Toast.LENGTH_LONG).show(); 30 } 31 } 32 33 } 34 }