---
title: "Android 判断网络"
author: "fonter"
date: "2010-05-19T15:28:23Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2010-05-19T15:29:21Z"
id: 669918
url: "https://fonter.iteye.com/blog/669918"
---

函数用于判断网络是否可用

 

```
/*  
*@return boolean return true if the application can access the internet  
*/  
private boolean haveInternet(){   
    NetworkInfo info=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();   
    if(info==null || !info.isConnected()){   
        return false;   
    }   
    if(info.isRoaming()){   
        //here is the roaming option you can change it if you want to disable internet while roaming, just return false   
        return true;   
    }   
    return true;   
}  
```

 

 

另一种方法

 

```
public boolean isNetworkAvailable() {   
   Context context = getApplicationContext();   
   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);   
   if (connectivity == null) {   
      boitealerte(this.getString(R.string.alert),"getSystemService rend null");   
   } 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;   
}  
```