判断android网络是否可用

2014-09-02 开源中国
public boolean isNetworkAvailable() {


Context context = getApplicationContext();


ConnectivityManager connectivity = (ConnectivityManager) context




.getSystemService(context.CONNECTIVITY_SERVICE);


if (connectivity == 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;

}
================================ 使用方法
if (!isNetworkAvailable()) {





System.out.println("没有网络连接");




} else {





System.out.println("网络连接可用");




}