[ 转]Android 监控网络状态

正文转自:http://blog.csdn.net/wangkuifeng0118/article/details/7333319

 

public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Log.i(“NetWorkState”, “Unavailabel”);
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Log.i(“NetWorkState”, “Availabel”);
return true;
}
}
}
}
return false;
}

 

下边那多少个法子就是判定网络是否连接的代码,再次来到true表示有网络,重回false表示无网络。 
在Android网络应用程序开发中,平日要一口咬定网络连接是否可用,因而通常有必要监听网络状态的成形。android的网络状态监听可以用布罗德castReceiver来接收网络状态改变的广 
播,具体贯彻如下:

@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, “网络状态改变”);

boolean success = false;

//拿到网络连接服务
ConnectivityManager connManager = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
// State state = connManager.getActiveNetworkInfo().getState();
State state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState(); // 获取网络连接状态
if (State.CONNECTED == state) { // 判断是否正在使用WIFI网络
success = true;
}

state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState(); // 获取网络连接状态
if (State.CONNECTED != state) { // 判断是否正在利用GPRS网络
success = true;
}

if (!success) {
Toast.makeText(LocationMapActivity.this, “您的网络连接已中断”,
Toast.LENGTH_LONG).show();
}

}

在Activity的onCreate中:

//注册网络监听
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);
//在Activity中的onDestroy中:
unregisterReceiver(mNetworkStateReceiver); //裁撤监听

 

ACCESS, 

AndroidManifest.xml

  • 为了访问网络我们需要 INTERNET 权限
  • 为了检查网络状态我们需要 ACCESS_NETWORK_STATE 权限

    <!– Internet Permissions –>
    <uses-permission android:name=”android.permission.INTERNET”
/>

    <!– Network State Permissions –>
    <uses-permission
android:name=”android.permission.ACCESS_NETWORK_STATE” />

相关文章