小工具知识网

当前位置: 首页 > 行业知识 > android 监听网络状态的变化及实战,安卓开发入门教程

行业知识

android 监听网络状态的变化及实战,安卓开发入门教程

2026-11-08 20:34:43 来源:互联网转载
  • Monitindex.php/tags-1038.html" >or network connections (Wi-Fi, GPRS, UMTS, etc.) (用来处理网络连接 ,包括Wi-Fi, GPRS, UMTS等)

  • 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(

  • Provide an API that allows applications to request and select networks for their data traffic

怎样获取ConnectivityManager对象呢?

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context

.CONNECTIVITY_SERVICE);

获取 NetworkInfo对象

主要有一下 几种方法

  • getNetworkInfo(int networkType),但是这个方法已经过时,官网的解释如下:This method was deprecated in API level 23. This method does not support multiple connected networks of the same type. Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.

  • getNetworkInfo(Network network)

  • getActiveNetwork()

Returns a Network object corresponding to the currently active default data network.

  • getActiveNetworkInfo(),Returns details about the currently active default data network.

  • getAllNetworkInfo()这个方法已经过时,Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.

综上所述,我们如果要知道当前Mobile网络或者WiFi网络是否已经连接上,总共有两种方法。

第一种方法,只不过在 API23的时候已经 过时了

State wifiState = null;

State mobileState = null;

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context

.CONNECTIVITY_SERVICE);

wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

Log.d(TAG1,

“wifi状态:” + wifiState + “\n mobile状态:” + mobileState);

if (wifiState != null && mobileState != null

&& State.CONNECTED != wifiState

&& State.CONNECTED == mobileState) {// 手机网络连接成功

Log.d(TAG1, “手机2g/3g/4g网络连接成功”);

APP.getInstance().setMobile(true);

APP.getInstance().setWifi(false);

APP.getInstance().setConnected(true);

} else if (wifiState != null && State.CONNECTED == wifiState) {// 无线网络连接成功

Log.d(TAG1, “无线网络连接成功”);

APP.getInstance().setMobile(false);

APP.getInstance().setWifi(true);

APP.getInstance().setConnected(true);

} else if (wifiState != null && mobileState != null

&& State.CONNECTED != wifiState

&& State.CONNECTED != mobileState) {// 手机没有任何的网络

Log.d(TAG1, “手机没有任何的网络”);

APP.getInstance().setMobile(false);

APP.getInstance().setWifi(false);

APP.getInstance().setConnected(false);

}

第二种方法

ConnectivityManager manager = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

Log.i(TAG1, “CONNECTIVITY_ACTION”);

NetworkInfo activeNetwork = manager.getActiveNetworkInfo();

if (activeNetwork != null)

上一篇:id模板打开秘籍,轻松上手,一键掌握打开方法!

下一篇:warthunder怎么换服务器?