ConnectivityManager getNetworkInfo (int)已弃用

使用 编译 SdkVersion 23,但是尝试支持最早的9。

getNetworkInfo(int) 在23。建议改用 getAllNetworks()getNetworkInfo(Network)。然而,这两者都需要最低的 API 21。

有没有一个类,我们可以在支持包中使用,可以帮助这一点?

我知道有人提出了一个解决方案 之前,但我的最低 API 要求9的挑战提出了一个问题。

135591 次浏览

你可使用:

GetActiveNetworkInfo () ;

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to mobile data
}
} else {
// not connected to the internet
}

或者在一个开关箱里

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
// connected to wifi
break;
case ConnectivityManager.TYPE_MOBILE:
// connected to mobile data
break;
default:
break;
}
} else {
// not connected to the internet
}

更新答案(19:07:2018) :

此方法将帮助您检查是否有可用的 Internet 连接。

public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


if (connectivityManager != null) {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return (activeNetwork != null && activeNetwork.isConnectedOrConnecting());
} else {
return false;
}
}

老答案:

为了实现最佳的代码重用实践,即兴创作 Cheese Bread 的答案。

public static boolean isNetworkAvailable(Context context) {
int[] networkTypes = {ConnectivityManager.TYPE_MOBILE,
ConnectivityManager.TYPE_WIFI};
try {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
for (int networkType : networkTypes) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null &&
activeNetworkInfo.getType() == networkType)
return true;
}
} catch (Exception e) {
return false;
}
return false;
}

该代码可以放置在 Util 类,可以用来检查电话是否连接到互联网通过 Wifi 或移动互联网从任何部分的应用程序。

作为 奶酪面包建议,使用 GetActiveNetworkInfo ()

GetActiveNetworkInfo

在 API 级别1中添加

NetworkInfogetActiveNetworkInfo ()

返回有关当前活动的默认数据网络的详细信息。连接时,此网络是传出连接的默认路由。在启动网络流量之前,应该始终检查 isConnected ()。当没有默认网络时,这可能返回 null。 此方法要求调用方持有权限 ACCESS _ NETWORK _ STATE。 报税表 网络资讯 当前默认网络的 NetworkInfo 对象,如果当前没有默认网络处于活动状态,则为 null。

参考文献: Android Studio

 public final boolean isInternetOn() {


// get Connectivity Manager object to check connection
ConnectivityManager connec =
(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);


// Check for network connections
if ( connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.CONNECTING ) {


// if connected with internet


Toast.makeText(this, connec.getActiveNetworkInfo().getTypeName(), Toast.LENGTH_LONG).show();
return true;


} else if (
connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {


Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
return false;
}
return false;
}

现在调用该方法,为了安全使用,请尝试 catch

try {
if (isInternetOn()) { /* connected actions */ }
else { /* not connected actions */ }
} catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}

别忘了加上:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

为了安全起见,我建议使用同样的方法

NetworkInfo.isConnected ()

整个方法可以如下:

/**
* Checking whether network is connected
* @param context Context to get {@link ConnectivityManager}
* @return true if Network is connected, else false
*/
public static boolean isConnected(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
int networkType = activeNetwork.getType();
return networkType == ConnectivityManager.TYPE_WIFI || networkType == ConnectivityManager.TYPE_MOBILE;
} else {
return false;
}
}

科特林版本:

fun isInternetOn(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
val activeNetwork = cm?.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}

由于张贴的答案只允许你查询活跃的网络,这里是如何得到 NetworkInfo的任何网络,而不仅仅是活跃的一个(例如 Wifi 网络)(对不起,科特林代码提前)

(getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).run {
allNetworks.find { getNetworkInfo(it).type == ConnectivityManager.TYPE_WIFI }?.let { network -> getNetworkInfo(network) }
//    getNetworkInfo(ConnectivityManager.TYPE_WIFI).isAvailable // This is the deprecated API pre-21
}

这需要 API 21或更高的权限和 android.permission.ACCESS_NETWORK_STATE

下面是我如何在最新的 Android 版本中检查当前的网络是否使用蜂窝网络:

val isCellular: Boolean get() {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm.getNetworkCapabilities(cm.activeNetwork).hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
} else {
cm.activeNetworkInfo?.type == ConnectivityManager.TYPE_MOBILE
}
}

至于2018年10月,公认的答案是不可接受的。

getType()以及类型本身现在在 API Level 28中已经被弃用:

调用者应该使用 NetworkCapability # TRANSPORT * 常量之一切换到检查 NetworkCapability # hasTransport

为了使用 NetworkCapabilities,您需要向 getNetworkCapabilities()方法传递一个 Network实例。要获得这个实例,您需要调用在 API Level 23中添加的 getActiveNetwork()

因此,我认为目前安全检查你是否连接到 Wi-Fi 或蜂窝网络的正确方法是:

public static boolean isNetworkConnected() {
final ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);


if (cm != null) {
if (Build.VERSION.SDK_INT < 23) {
final NetworkInfo ni = cm.getActiveNetworkInfo();


if (ni != null) {
return (ni.isConnected() && (ni.getType() == ConnectivityManager.TYPE_WIFI || ni.getType() == ConnectivityManager.TYPE_MOBILE));
}
} else {
final Network n = cm.getActiveNetwork();


if (n != null) {
final NetworkCapabilities nc = cm.getNetworkCapabilities(n);


return (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI));
}
}
}


return false;
}

您还可以检查其他类型的 TRANSPORT,您可以找到 给你

重要提示: 如果您连接到 Wi-Fi 还有到 VPN,那么您当前的状态可能是 TRANSPORT_VPN,因此您可能还需要检查它。

不要忘记向你的 AndroidManifest 文件添加以下权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

2020年2月更新:

已接受的答案在 28 (Android P)中再次被弃用,但是它的替换方法只在 23 (Android M)上有效。为了支持旧设备,我用 Kotlin 和 Java 编写了一个 helper 函数。

使用方法:

int type = getConnectionType(getApplicationContext());

它返回一个 int,你可以在你的代码中把它改成 enum:

0: 没有可用的互联网(可能是在飞行模式,或在加入无线网络的过程中)。

1: 蜂窝(移动数据,3G/4G/LTE 等等)。

2: Wi-fi 无线网络。

第3集: VPN

您可以复制 helper 函数的 Kotlin 或 Java 版本。

科特林:

@IntRange(from = 0, to = 3)
fun getConnectionType(context: Context): Int {
var result = 0 // Returns connection type. 0: none; 1: mobile data; 2: wifi; 3: vpn
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm?.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2
} else if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1
} else if (hasTransport(NetworkCapabilities.TRANSPORT_VPN)){
result = 3
}
}
}
} else {
cm?.run {
cm.activeNetworkInfo?.run {
if (type == ConnectivityManager.TYPE_WIFI) {
result = 2
} else if (type == ConnectivityManager.TYPE_MOBILE) {
result = 1
} else if(type == ConnectivityManager.TYPE_VPN) {
result = 3
}
}
}
}
return result
}

Java:

@IntRange(from = 0, to = 3)
public static int getConnectionType(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi; 3: vpn
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = 3;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = 2;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = 1;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
result = 3;
}
}
}
}
return result;
}

这个被接受的答案在28版本中是不推荐的,所以这里是我在我的项目中使用的解决方案。

返回连接类型。 false: 无 Internet 连接; true: mobile 无线数据

public static boolean isNetworkConnected(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}

(几乎)所有的答案在 Android P 中都不被认可。

返回文章页面

public boolean IsOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


if (cm == null) return false;


if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
NetworkInfo ni = cm.getActiveNetworkInfo();


if (ni == null) return false;


return ni.isConnected() && (ni.getType() == ConnectivityManager.TYPE_WIFI || ni.getType() == ConnectivityManager.TYPE_MOBILE);
}


NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());


if (nc == null) return false;


return nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
}

返回文章页面

public bool IsOnline(Context context)
{
var cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
   

if (cm == null) return false;


if (Build.VERSION.SdkInt < BuildVersionCodes.M)
{
var ni = cm.ActiveNetworkInfo;


if (ni == null) return false;


return ni.IsConnected && (ni.Type == ConnectivityType.Wifi || ni.Type == ConnectivityType.Mobile);
}


return cm.GetNetworkCapabilities(cm.ActiveNetwork).HasTransport(Android.Net.TransportType.Wifi)
|| cm.GetNetworkCapabilities(cm.ActiveNetwork).HasTransport(Android.Net.TransportType.Cellular);
}

这里的关键是 NetworkCapabilities.TRANSPORT_XXX(Android.Net.TransportType)

这个答案在2020年3月有一个更新,它支持 API.15到 API.29,你可以在原答案后面找到它

回答2019年2月

检查你是否在线:

boolean isOnline() {
// Checking internet connectivity
ConnectivityManager connectivityMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (connectivityMgr != null) {
activeNetwork = connectivityMgr.getActiveNetworkInfo();
}
return activeNetwork != null;
}

科特林:

fun isOnline(): Boolean {
val connectivityMgr = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager


if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return connectivityMgr.activeNetworkInfo != null


} else {


for (network in connectivityMgr.allNetworks) { // added in API 21 (Lollipop)
val networkCapabilities: NetworkCapabilities? =
connectivityMgr.getNetworkCapabilities(network)
return (networkCapabilities!!.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) &&
(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)))
}
}
return false
}

获取机器人 M 之前/之后的互联网连接类型

void internetType() {
// Checking internet connectivity
ConnectivityManager connectivityMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (connectivityMgr != null) {
activeNetwork = connectivityMgr.getActiveNetworkInfo();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities nc = connectivityMgr.getNetworkCapabilities(connectivityMgr.getActiveNetwork());
if (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
// connected to mobile data
} else if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
// connected to wifi
}
} else {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to mobile data
}
}
}
}

所有情况都需要访问网络状态的权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

2020年12月最新情况

由于 NetworkInfo已被废弃,而从 API 29开始,我们必须使用 ConnectivityManager.NetworkCallback,同时改变其网络状态 onAvailable()onLost()回调。

用法:

  • 您可以使用 这个图书馆,也可以直接使用下面的代码 实用程序类,它是这个库的一部分。

特征

  • 它的生命周期意识通过实现 LifecycleObserver来避免内存泄漏,在 onDestroy()方法中进行一些清理。
  • 它支持从 API 15(冰淇淋三明治)到 API 29(Android Q)
  • 对于 API 21之前的 API,它使用基于上下文的 BoradcastReceiverNetworkInfo,对于 API 21及以上的 API 使用 ConnectivityManager.NetworkCallback
  • 当 WiFi 和蜂窝网络都打开时,连接监听器在转移到蜂窝网络时不会中断 WiFi 的连接。
  • 当蜂窝网络开启时,连接侦听器不会在 WiFi 连接并成为活动网络时中断(因为这是首选网络)。
  • 如果要使用这个库,那么就不需要包含这个权限 android.permission.ACCESS_NETWORK_STATE; 但是如果要使用实用程序类,就必须包含它。

能力

  • 获取当前连接状态(联机/脱机)。
  • 持续检查/监听互联网连接及 当设备脱机或联机时触发回调。
  • 获取活动互联网连接的类型(WiFi 或蜂窝)。
  • 获取所有可用网络的类型(WiFi 或蜂窝)。 > > 仅 支持 API 21 +
  • 获取所有可用网络的数量 > > 仅支持 API 21 +
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public class ConnectionUtil implements LifecycleObserver {


private static final String TAG = "LOG_TAG";
private ConnectivityManager mConnectivityMgr;
private Context mContext;
private NetworkStateReceiver mNetworkStateReceiver;
    

/*
* boolean indicates if my device is connected to the internet or not
* */
private boolean mIsConnected = false;
private ConnectionMonitor mConnectionMonitor;




/**
* Indicates there is no available network.
*/
private static final int NO_NETWORK_AVAILABLE = -1;




/**
* Indicates this network uses a Cellular transport.
*/
public static final int TRANSPORT_CELLULAR = 0;




/**
* Indicates this network uses a Wi-Fi transport.
*/
public static final int TRANSPORT_WIFI = 1;




public interface ConnectionStateListener {
void onAvailable(boolean isAvailable);
}




public ConnectionUtil(Context context) {
mContext = context;
mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
((AppCompatActivity) mContext).getLifecycle().addObserver(this);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mConnectionMonitor = new ConnectionMonitor();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
mConnectivityMgr.registerNetworkCallback(networkRequest, mConnectionMonitor);
}


}




/**
* Returns true if connected to the internet, and false otherwise
*
* <p>
* NetworkInfo is deprecated in API 29
* https://developer.android.com/reference/android/net/NetworkInfo
* <p>
* getActiveNetworkInfo() is deprecated in API 29
* https://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetworkInfo()
* <p>
* getNetworkInfo(int) is deprecated as of API 23
* https://developer.android.com/reference/android/net/ConnectivityManager#getNetworkInfo(int)
*/
public boolean isOnline() {


mIsConnected = false;


if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
// Checking internet connectivity
NetworkInfo activeNetwork = null;
if (mConnectivityMgr != null) {
activeNetwork = mConnectivityMgr.getActiveNetworkInfo(); // Deprecated in API 29
}
mIsConnected = activeNetwork != null;


} else {
Network[] allNetworks = mConnectivityMgr.getAllNetworks(); // added in API 21 (Lollipop)


for (Network network : allNetworks) {
NetworkCapabilities networkCapabilities = mConnectivityMgr.getNetworkCapabilities(network);
if (networkCapabilities != null) {
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED))
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
mIsConnected = true;
}
}


}


return mIsConnected;


}




/**
* Returns
* <p> <p>
* <p><p> NO_NETWORK_AVAILABLE >>> when you're offline
* <p><p> TRANSPORT_CELLULAR >> When Cellular is the active network
* <p><p> TRANSPORT_WIFI >> When Wi-Fi is the Active network
* <p>
*/
public int getActiveNetwork() {


NetworkInfo activeNetwork = mConnectivityMgr.getActiveNetworkInfo(); // Deprecated in API 29
if (activeNetwork != null)


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = mConnectivityMgr.getNetworkCapabilities(mConnectivityMgr.getActiveNetwork());
if (capabilities != null)
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
// connected to mobile data
return TRANSPORT_CELLULAR;


} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
// connected to wifi
return TRANSPORT_WIFI;
}


} else {
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { // Deprecated in API 28
// connected to mobile data
return TRANSPORT_CELLULAR;


} else if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { // Deprecated in API 28
// connected to wifi
return TRANSPORT_WIFI;
}
}
return NO_NETWORK_AVAILABLE;
}




@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int getAvailableNetworksCount() {


int count = 0;


if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Network[] allNetworks = mConnectivityMgr.getAllNetworks(); // added in API 21 (Lollipop)
for (Network network : allNetworks) {
NetworkCapabilities networkCapabilities = mConnectivityMgr.getNetworkCapabilities(network);
if (networkCapabilities != null)
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR))
count++;
}


}


return count;
}
    



@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public List<Integer> getAvailableNetworks() {


List<Integer> activeNetworks = new ArrayList<>();


Network[] allNetworks; // added in API 21 (Lollipop)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
allNetworks = mConnectivityMgr.getAllNetworks();
for (Network network : allNetworks) {
NetworkCapabilities networkCapabilities = mConnectivityMgr.getNetworkCapabilities(network);
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
activeNetworks.add(TRANSPORT_WIFI);


if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR))
activeNetworks.add(TRANSPORT_CELLULAR);


}
}
}


return activeNetworks;
}




public void onInternetStateListener(ConnectionStateListener listener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mNetworkStateReceiver = new NetworkStateReceiver(listener);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mNetworkStateReceiver, intentFilter);


} else {
mConnectionMonitor.setOnConnectionStateListener(listener);
}
}




@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "onDestroy");
((AppCompatActivity) mContext).getLifecycle().removeObserver(this);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mConnectionMonitor != null)
mConnectivityMgr.unregisterNetworkCallback(mConnectionMonitor);
} else {
if (mNetworkStateReceiver != null)
mContext.unregisterReceiver(mNetworkStateReceiver);
}


}




public class NetworkStateReceiver extends BroadcastReceiver {


ConnectionStateListener mListener;


public NetworkStateReceiver(ConnectionStateListener listener) {
mListener = listener;
}


@Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {


NetworkInfo activeNetworkInfo = mConnectivityMgr.getActiveNetworkInfo(); // deprecated in API 29


/*
* activeNetworkInfo.getState() deprecated in API 28
* NetworkInfo.State.CONNECTED deprecated in API 29
* */
if (!mIsConnected && activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
Log.d(TAG, "onReceive: " + "Connected To: " + activeNetworkInfo.getTypeName());
mIsConnected = true;
mListener.onAvailable(true);


} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
if (!isOnline()) {
mListener.onAvailable(false);
mIsConnected = false;
}


}


}
}
}




@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ConnectionMonitor extends ConnectivityManager.NetworkCallback {


private ConnectionStateListener mConnectionStateListener;


void setOnConnectionStateListener(ConnectionStateListener connectionStateListener) {
mConnectionStateListener = connectionStateListener;
}


@Override
public void onAvailable(@NonNull Network network) {


if (mIsConnected)
return;


Log.d(TAG, "onAvailable: ");


if (mConnectionStateListener != null) {
mConnectionStateListener.onAvailable(true);
mIsConnected = true;
}


}


@Override
public void onLost(@NonNull Network network) {


if (getAvailableNetworksCount() == 0) {
if (mConnectionStateListener != null)
mConnectionStateListener.onAvailable(false);
mIsConnected = false;
}


}


}


}

Kotlin 版本


class ConnectionUtil(var mContext: Context) : LifecycleObserver {


private val TAG = "LOG_TAG"


companion object NetworkType {


/**
* Indicates this network uses a Cellular transport.
*/
const val TRANSPORT_CELLULAR = 0


/**
* Indicates this network uses a Wi-Fi transport.
*/
const val TRANSPORT_WIFI = 1


}


private var mConnectivityMgr: ConnectivityManager? = null


//    private var mContext: Context? = null
private var mNetworkStateReceiver: NetworkStateReceiver? = null


/*
* boolean indicates if my device is connected to the internet or not
* */
private var mIsConnected = false
private var mConnectionMonitor: ConnectionMonitor? = null




/**
* Indicates there is no available network.
*/
private val NO_NETWORK_AVAILABLE = -1




interface ConnectionStateListener {
fun onAvailable(isAvailable: Boolean)
}


init {
mConnectivityMgr =
mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
(mContext as AppCompatActivity?)!!.lifecycle.addObserver(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mConnectionMonitor = ConnectionMonitor()
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build()
mConnectivityMgr!!.registerNetworkCallback(networkRequest, mConnectionMonitor!!)
}
}




/**
* Returns true if connected to the internet, and false otherwise
*
* NetworkInfo is deprecated in API 29
* https://developer.android.com/reference/android/net/NetworkInfo
*
* getActiveNetworkInfo() is deprecated in API 29
* https://developer.android.com/reference/android/net/ConnectivityManager#getActiveNetworkInfo()
*
* getNetworkInfo(int) is deprecated as of API 23
* https://developer.android.com/reference/android/net/ConnectivityManager#getNetworkInfo(int)
*/
fun isOnline(): Boolean {
mIsConnected = false
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
// Checking internet connectivity
var activeNetwork: NetworkInfo? = null
if (mConnectivityMgr != null) {
activeNetwork = mConnectivityMgr!!.activeNetworkInfo // Deprecated in API 29
}
mIsConnected = activeNetwork != null
} else {
val allNetworks = mConnectivityMgr!!.allNetworks // added in API 21 (Lollipop)
for (network in allNetworks) {
val networkCapabilities = mConnectivityMgr!!.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
)
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
) mIsConnected = true
}
}
}
return mIsConnected
}




/**
* Returns:
*
* NO_NETWORK_AVAILABLE >>> when you're offline
* TRANSPORT_CELLULAR >> When Cellular is the active network
* TRANSPORT_WIFI >> When Wi-Fi is the Active network
*/
fun getActiveNetwork(): Int {
val activeNetwork = mConnectivityMgr!!.activeNetworkInfo // Deprecated in API 29
if (activeNetwork != null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = mConnectivityMgr!!.getNetworkCapabilities(
mConnectivityMgr!!.activeNetwork
)
if (capabilities != null) if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
// connected to mobile data
return TRANSPORT_CELLULAR
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
// connected to wifi
return TRANSPORT_WIFI
}
} else {
if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) { // Deprecated in API 28
// connected to mobile data
return TRANSPORT_CELLULAR
} else if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) { // Deprecated in API 28
// connected to wifi
return TRANSPORT_WIFI
}
}
return NO_NETWORK_AVAILABLE
}




@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
fun getAvailableNetworksCount(): Int {
var count = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val allNetworks = mConnectivityMgr!!.allNetworks // added in API 21 (Lollipop)
for (network in allNetworks) {
val networkCapabilities = mConnectivityMgr!!.getNetworkCapabilities(network)
if (networkCapabilities != null) if (networkCapabilities.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI
)
|| networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
) count++
}
}
return count
}


@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
fun getAvailableNetworks(): List<Int> {
val activeNetworks: MutableList<Int> = ArrayList()
val allNetworks: Array<Network> // added in API 21 (Lollipop)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
allNetworks = mConnectivityMgr!!.allNetworks
for (network in allNetworks) {
val networkCapabilities = mConnectivityMgr!!.getNetworkCapabilities(network)
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) activeNetworks.add(
TRANSPORT_WIFI
)
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) activeNetworks.add(
TRANSPORT_CELLULAR
)
}
}
}
return activeNetworks
}




fun onInternetStateListener(listener: ConnectionStateListener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mNetworkStateReceiver = NetworkStateReceiver(listener)
val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
mContext.registerReceiver(mNetworkStateReceiver, intentFilter)
} else {
mConnectionMonitor!!.setOnConnectionStateListener(listener)
}
}




@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.d(TAG, "onDestroy")
(mContext as AppCompatActivity?)!!.lifecycle.removeObserver(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mConnectionMonitor != null) mConnectivityMgr!!.unregisterNetworkCallback(
mConnectionMonitor!!
)
} else {
if (mNetworkStateReceiver != null) mContext.unregisterReceiver(mNetworkStateReceiver)
}
}




inner class NetworkStateReceiver(var mListener: ConnectionStateListener) :
BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.extras != null) {
val activeNetworkInfo: NetworkInfo? =
mConnectivityMgr?.getActiveNetworkInfo() // deprecated in API 29


/*
* activeNetworkInfo.getState() deprecated in API 28
* NetworkInfo.State.CONNECTED deprecated in API 29
* */if (!mIsConnected && activeNetworkInfo != null && activeNetworkInfo.state == NetworkInfo.State.CONNECTED) {
mIsConnected = true
mListener.onAvailable(true)
} else if (intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY,
java.lang.Boolean.FALSE
)
) {
if (!isOnline()) {
mListener.onAvailable(false)
mIsConnected = false
}
}
}
}
}


@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
inner class ConnectionMonitor : NetworkCallback() {
private var mConnectionStateListener: ConnectionStateListener? = null
fun setOnConnectionStateListener(connectionStateListener: ConnectionStateListener?) {
mConnectionStateListener = connectionStateListener
}


override fun onAvailable(network: Network) {
if (mIsConnected) return
Log.d(TAG, "onAvailable: ")
if (mConnectionStateListener != null) {
mConnectionStateListener!!.onAvailable(true)
mIsConnected = true
}
}


override fun onLost(network: Network) {
if (getAvailableNetworksCount() == 0) {
mConnectionStateListener?.onAvailable(false)
mIsConnected = false
}
}
}


}

最好检查你的网络是否连接到互联网:

@Suppress("DEPRECATION")
fun isNetworkAvailable(context: Context): Boolean {
try {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT > 22) {
val an = cm.activeNetwork ?: return false
val capabilities = cm.getNetworkCapabilities(an) ?: return false
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
} else {
val a = cm.activeNetworkInfo ?: return false
a.isConnected && (a.type == ConnectivityManager.TYPE_WIFI || a.type == ConnectivityManager.TYPE_MOBILE)
}
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
public boolean isConnectedToWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
}


if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
if (capabilities == null) {
return false;
}
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo == null) {
return false;
}
return networkInfo.isConnected();
}
}

我们可能需要多次检查互联网连接。因此,如果我们使用 Context的扩展方法来编写代码块,将会更加容易。下面是 ContextFragment的助手扩展。

检查互联网连接

fun Context.hasInternet(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT < 23) {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
activeNetworkInfo != null && activeNetworkInfo.isConnected
} else {
val nc = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (nc == null) {
false
} else {
nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}
}
}

其他延伸部分

fun Context.hasInternet(notifyNoInternet: Boolean = true, trueFunc: (internet: Boolean) -> Unit) {
if (hasInternet()) {
trueFunc(true)
} else if (notifyNoInternet) {
Toast.makeText(this, "No Internet Connection!", Toast.LENGTH_SHORT).show()
}
}


fun Context.hasInternet(
trueFunc: (internet: Boolean) -> Unit,
falseFunc: (internet: Boolean) -> Unit
) {
if (hasInternet()) {
trueFunc(true)
} else {
falseFunc(true)
}
}


fun Fragment.hasInternet(): Boolean = context!!.hasInternet()


fun Fragment.hasInternet(notifyNoInternet: Boolean = true, trueFunc: (internet: Boolean) -> Unit) =
context!!.hasInternet(notifyNoInternet, trueFunc)


fun Fragment.hasInternet(
trueFunc: (internet: Boolean) -> Unit, falseFunc: (internet: Boolean) -> Unit
) = context!!.hasInternet(trueFunc, falseFunc)

检查互联网是否可用:

@RequiresPermission(allOf = [
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.INTERNET
])
fun isInternetAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}

NetManager ,你可以使用 < strong > Kotlin 在 Android 上检查互联网连接

如果你使用 MinSdkVersion > = 23

class NetManager @Inject constructor(var applicationContext: Context) {
val isConnectedToInternet: Boolean?
get() = with(
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
) {
isConnectedToInternet()
}
}


fun ConnectivityManager.isConnectedToInternet() = isConnected(getNetworkCapabilities(activeNetwork))


fun isConnected(networkCapabilities: NetworkCapabilities?): Boolean {
return when (networkCapabilities) {
null -> false
else -> with(networkCapabilities) { hasTransport(TRANSPORT_CELLULAR) || hasTransport(TRANSPORT_WIFI) }
}
}

如果你使用 MinSdkVersion < 23

class NetManager @Inject constructor(var applicationContext: Context) {
val isConnectedToInternet: Boolean?
get() = with(
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
) {
isConnectedToInternet()
}
}


fun ConnectivityManager.isConnectedToInternet(): Boolean = if (Build.VERSION.SDK_INT < 23) {
isConnected(activeNetworkInfo)
} else {
isConnected(getNetworkCapabilities(activeNetwork))
}




fun isConnected(network: NetworkInfo?): Boolean {
return when (network) {
null -> false
else -> with(network) { isConnected && (type == TYPE_WIFI || type == TYPE_MOBILE) }
}
}


fun isConnected(networkCapabilities: NetworkCapabilities?): Boolean {
return when (networkCapabilities) {
null -> false
else -> with(networkCapabilities) { hasTransport(TRANSPORT_CELLULAR) || hasTransport(TRANSPORT_WIFI) }
}
}

GetActiveNetwork ()不在 android M (API 28)下面。 GetState ()不推荐使用在 android L 之上。

所以,最终的答案是:

public static boolean isConnectingToInternet(Context mContext) {
if (mContext == null) return false;


ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Network network = connectivityManager.getActiveNetwork();
if (network != null) {
final NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(network);


return (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI));
}
} else {
NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
for (NetworkInfo tempNetworkInfo : networkInfos) {
if (tempNetworkInfo.isConnected()) {
return true;
}
}
}
}
return false;
}

我在 Kotlin 就行。许多 API 在 Network Manager 类中是不推荐的,所以下面的答案涵盖了所有 API 支持。

fun isNetworkAvailable(context: Context): Boolean {
var result = false
(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
result = isCapableNetwork(this,this.activeNetwork)
} else {
val networkInfos = this.allNetworks
for (tempNetworkInfo in networkInfos) {
if(isCapableNetwork(this,tempNetworkInfo))
result =  true
}
}
}


return result
}


fun isCapableNetwork(cm: ConnectivityManager,network: Network?): Boolean{
cm.getNetworkCapabilities(network)?.also {
if (it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true
} else if (it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true
}
}
return false
}

您还将在下面添加

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

下面的代码适用于所有 API

然而,getActiveNetworkInfo ()仅在 API 29中被弃用,并且适用于所有 API,因此我们可以在所有 API 低于29的 API 中使用它

fun isInternetAvailable(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}


}
}
}


return result
}

许多答案仍然使用低于23的 GetNetworkType,这是不推荐的; 使用以下代码检查设备是否有互联网连接。

public static boolean isNetworkConnected(Context context) {


ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


if (cm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
} else {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}


return false;
}

..

并且,不要忘记在 Manifest 中添加这一行

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Https://www.agnosticdev.com/content/how-detect-network-connectivity-android

请按照这个教程,它应该帮助任何人寻找答案。

注意 networkInfo 已被弃用,因此替换为 isNetworkReacheable () 下面是@vidha 的回答 传递 getApplicationContext ()作为参数

  public static boolean isNetworkReacheable(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}

就像这样:

public boolean hasConnection(final Context context){
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNW = cm.getActiveNetworkInfo();
if (activeNW != null && activeNW.isConnected())
{
return true;
}
return false;
}

在主程序主体中:

if(hasConnection(this)) {
Toast.makeText(this, "Active networks OK ", Toast.LENGTH_LONG).show();
getAccountData(token, tel);
}
else  Toast.makeText(this, "No active networks... ", Toast.LENGTH_LONG).show();

这在 Android 10中也可以使用,如果连接到互联网,返回 true,否则返回 false。

private fun isOnline(): Boolean {
val connectivityManager =
getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
return true
}
}
}
return false
}

这可以帮助别人 科特林

fun isNetworkConnected(context: Context) : Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities =  connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
capabilities.also {
if (it != null){
if (it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
return true
else if (it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
return true
}
}
}
return false
}

使用 目标 SDK 29 检查网络状态:

@IntRange(from = 0, to = 3)
fun getConnectionType(context: Context): Int {
var result = 0 // Returns connection type. 0: none; 1: mobile data; 2: wifi
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities =
cm.getNetworkCapabilities(cm.activeNetwork)
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = 3
}
}
} else {
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.type === ConnectivityManager.TYPE_WIFI) {
result = 2
} else if (activeNetwork.type === ConnectivityManager.TYPE_MOBILE) {
result = 1
} else if (activeNetwork.type === ConnectivityManager.TYPE_VPN) {
result = 3
}
}
}
return result
}

对于 Android M (api 23) ,一些属性(例如 getActiveNetworkInfo())不推荐使用。

结合这里的一些答案,以及最新的指南和 API,在 Kotlin 成为一个非常有用的扩展功能。在单独的文件中,您可以编写以下内容:

fun Context.hasNetwork(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkConnected(connectivityManager)
} else {
checkConnectedLegacy(connectivityManager)
}
}


@RequiresApi(Build.VERSION_CODES.M)
fun checkConnected(connectivityManager: ConnectivityManager): Boolean {
val activeNetwork = connectivityManager.activeNetwork
activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork)
capabilities ?: return false
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}


fun checkConnectedLegacy(connectivityManager: ConnectivityManager): Boolean {
val networkInfo = connectivityManager.activeNetworkInfo
networkInfo ?: return false
return networkInfo.isConnected && (networkInfo.type == ConnectivityManager.TYPE_WIFI || networkInfo.type == ConnectivityManager.TYPE_MOBILE)
}

这样你就可以在任何可以访问上下文的地方编写下面的代码,例如:

 if (requireContext().hasNetwork()) {
// do whatever if you HAVE network
} else {
// handle no network state
}