Android 判断网络是否可用

时间:2021-02-04 22:17:05

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkDetector {
 /**
  * 判断网络是否可用
  * @param act
  * @return
  */
 public static Boolean detect(Activity act) {
  ConnectivityManager manager = (ConnectivityManager) act
    .getApplicationContext().getSystemService(
      Context.CONNECTIVITY_SERVICE);
  if (manager == null) {
   return false;
  }
  NetworkInfo networkinfo = manager.getActiveNetworkInfo();
  if (networkinfo == null || !networkinfo.isAvailable()) {
   return false;
  }
  return true;
 }
}

因为以上代码用到了权限,需要在AndroidManifest文件中加入如下权限代码:

    <uses-permission

       android:name="android.permission.ACCESS_NETWORK_STATE" />