您的位置:首页 > 理论基础 > 计算机网络

Android 获取网络状态及调用网络配置界面(转帖)

2011-07-14 16:47 405 查看
/article/5496881.html

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 calling
Context.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网络设置界面

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: