怎样检查Android网络连接状态

2014-11-24 11:47:44 · 作者: · 浏览: 2

< xml version="1.0" encoding="utf-8" >
package="com.example.detectinternetconnection"
android:versionCode="1"
android:versionName="1.0" >



android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
android:name=".AndroidDetectInternetConnectionActivity"
android:label="@string/app_name" >















package com.example.detectinternetconnection;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
this._context = context;
}

public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
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;
}
}


ConnectionDetector cd = new ConnectionDetector(getApplicationContext());

Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false