ndroid平台提供了ConnectivityManager 类,用于网络连接状态的检测。
Android开发文档这样描述ConnectivityManager 的作用:
Class that answers queries about the state of network connectivity. It also notifies applications when network connectivity changes. Get an instance of this class by callingContext.getSystemService(Context.CONNECTIVITY_SERVICE).
The primary responsibilities of this class are to:
- Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
- Send broadcast intents when network connectivity changes
- Attempt to "fail over" to another network when connectivity to a network is lost
- Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
注:
根据Android的安全机制,在使用ConnectivityManager时,必须在AndroidManifest.xml中添加<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 否则无法获得系统的许可。
private void checkNetworkInfo()
{
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile 3G Data Network
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
txt3G.setText(mobile.toString());
//wifi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
txtWifi.setText(wifi.toString());
//如果3G网络和wifi网络都未连接,且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
if(mobile==State.CONNECTED||mobile==State.CONNECTING)
return;
if(wifi==State.CONNECTED||wifi==State.CONNECTING)
return;
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));//进入无线网络配置界面
//startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //进入手机中的wifi网络设置界面
}
本文介绍如何使用Android平台提供的ConnectivityManager类来检测网络连接状态。包括监测Wi-Fi、3G等网络连接情况,并在连接发生变化时发送广播意图。还介绍了如何在AndroidManifest.xml中添加必要的权限。
382

被折叠的 条评论
为什么被折叠?



