1. 程式人生 > >android聯網工具類

android聯網工具類

 聯網工具類 1.判斷網路是否可用  2.判斷網路是否已連線  3.獲取網路型別 4.判斷是否是WiFi網路   5. 判斷是否是Mobile網路

// 判斷網路是否可用

 public static boolean isNetworkAvailable(Context context) {

  // ConnectivityManager:網路連線管理器.負責迴應網路的連線狀態.

  // ①.Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)

  // 監視網路連線;

  // ②.Send broadcast intents when network connectivity changes

  // 當網路連線發生改變的時候傳送一個廣播意圖;

  // ③.Attempt to "fail over" to another network when connectivity to a

  // network is lost

  // 當與一個網路斷開的時候,嘗試著進行"故障轉移"到另一個網路;

  // ④.Provide an API that allows applications to query the coarse-grained

  // or fine-grained state of the available networks

  // 提供了一套API來查詢當前可用的網路的"好與壞".

  // ⑤.Provide an API that allows applications to request and select

  // networks for their data traffic

  // 提供了一套API供應用程式來進行網路中資料的傳遞.

  ConnectivityManager manager = (ConnectivityManager) context

    .getSystemService(Context.CONNECTIVITY_SERVICE);

  // 得到一個網路資訊類

  NetworkInfo info = manager.getActiveNetworkInfo();

  if (info != null) {

   // 判斷網路是否可用

   return info.isAvailable();

  }

  return false;

 }

=====================================================================

// 判斷網路是否已連線

 public static boolean isNetworkConnected(Context context) {

  ConnectivityManager manager = (ConnectivityManager) context

    .getSystemService(Context.CONNECTIVITY_SERVICE);

  NetworkInfo info = manager.getActiveNetworkInfo();

  if (info != null) {

   return info.isConnected();

  }

  return false;

 }

=====================================================================

 // 獲取網路型別

 public static String getNetworkType(Context context) {

  ConnectivityManager manager = (ConnectivityManager) context

    .getSystemService(Context.CONNECTIVITY_SERVICE);

  NetworkInfo info = manager.getActiveNetworkInfo();

  if (info != null) {

   // 返回網路型別.

   // int type = info.getType();

   // 返回人類可讀的網路型別

   return info.getTypeName();

  }

  return null;

 }

=====================================================================



// 判斷是否是WiFi網路

 @SuppressWarnings("deprecation")

 public static boolean isWifiNetwork(Context context) {

  ConnectivityManager manager = (ConnectivityManager) context

    .getSystemService(Context.CONNECTIVITY_SERVICE);

  NetworkInfo networkInfo = manager

    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

  if (networkInfo != null && networkInfo.isConnected()) {

   return true;

  }

  return false;

 }

=====================================================================

 // 判斷是否是Mobile網路

 @SuppressWarnings("deprecation")

 public static boolean isMobileNetwork(Context context) {

  ConnectivityManager manager = (ConnectivityManager) context

    .getSystemService(Context.CONNECTIVITY_SERVICE);

  NetworkInfo networkInfo = manager

    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

  if (networkInfo != null && networkInfo.isConnected()) {

   return true;

  }

  return false;

 }

}