使用compileSdkVersion 23,但是尝试支持早至9。
getNetworkInfo(int)
在23中被弃用。建议使用getAllNetworks()
和getNetworkInfo(Network)
代替。但是,这两个都需要最少的API 21。
我们可以在支持包中使用一个可以帮助您解决问题的类吗?
使用compileSdkVersion 23,但是尝试支持早至9。
getNetworkInfo(int)
在23中被弃用。建议使用getAllNetworks()
和getNetworkInfo(Network)
代替。但是,这两个都需要最少的API 21。
我们可以在支持包中使用一个可以帮助您解决问题的类吗?
Answers:
您可以使用:
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
}
activeNetwork.getType()
被弃用和ConnectivityManager.TYPE_WIFI
弃用
cm.getNetworkCapabilities(cm.activeNetwork).hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
截至2018年10月,已弃用已接受的答案。
getType()
以及类型本身,现在在API级别28中已弃用。从Javadoc:
呼叫者应改用检查NetworkCapabilities#hasTransport而不是使用NetworkCapabilities#TRANSPORT *常量之一
为了使用NetworkCapabilities
,您需要将Network
实例传递给getNetworkCapabilities()
方法。要获取该实例,您需要调用getActiveNetwork()
API级别23中添加的实例。
因此,我认为目前安全检查您是否已连接到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" />
NetworkInfo
贬值,您将无法再使用NetWorkInfo
,那么这如何提供替代方案?
2020年2月更新:
接受的答案再次被弃用28 (Android P)
,但其替换方法仅适用于23 (Android M)
。为了支持较旧的设备,我在中编写了一个辅助函数。
如何使用:
int type = getConnectionType(getApplicationContext());
它返回int
,您可以enum
在代码中将其更改为:
0:没有可用的互联网(可能处于飞行模式,或者正在加入Wi-Fi)。
1:蜂窝(移动数据,3G / 4G / LTE等)。
2:Wi-Fi。
3:VPN
您可以复制辅助功能的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
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
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;
}
No Internet
,Cellular
和Wi-Fi
。如果您不关心连接类型,请随时修改代码以适合您的应用程序。
Boolean
包装器类而不是boolean
原始类,则必须小心。在if语句中,您将必须添加check null
。如果明天在NetworkCapabilities中引入了另一种新的传输模式,那么该怎么办...所以使用整数进行分支将有所帮助,并且您还可以进行切换。
更新的答案(19:07:2018):
此方法将帮助您检查互联网连接是否可用。
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;
}
}
旧答案:
为了获得最佳的代码重用实践,请即兴做出芝士面包的答案。
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或Mobile Internet连接到Internet。
activeNetwork.isConnectedOrConnecting()
现在已弃用
可接受的答案在版本28中已弃用,因此这是我在项目中使用的解决方案。
返回连接类型。false:没有Internet连接;true:移动数据|| 无线上网
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;
}
截至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;
}
在android M之前/之后获取Internet连接的类型
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年3月更新
从NetworkInfo
过时开始,从API 29开始,我们必须使用ConnectivityManager.NetworkCallback
其网络状态更改onAvailable()
和onLost()
回调。
用法:
特征
LifecycleObserver
对onDestroy()
方法进行一些清理来实现避免内存泄漏的方式来实现生命周期意识。BoradcastReceiver
和NetworkInfo
,并ConnectivityManager.NetworkCallback
用于API 21及更高版本。android.permission.ACCESS_NETWORK_STATE
;但是如果要使用实用程序类,则必须包括它。能力
@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.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) {
mConnectionStateListener.onAvailable(false);
mIsConnected = false;
}
}
}
}
onLost
将被呼叫。onLost
并不意味着设备断开了互联网连接,而是网络断开了连接。
最好检查您的网络是否连接到Internet:
@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
}
如奶酪面包建议的那样,使用 getActiveNetworkInfo()
getActiveNetworkInfo
在API级别1中添加
NetworkInfo getActiveNetworkInfo()
返回有关当前活动的默认数据网络的详细信息。连接后,此网络是传出连接的默认路由。在启动网络流量之前,应始终检查isConnected()。如果没有默认网络,则可能返回null。此方法要求调用方持有权限ACCESS_NETWORK_STATE。返回NetworkInfo一个当前默认网络的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" />
getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).isAvailable
为了安全起见,我建议也使用方法
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;
}
}
activeNetwork.getType()
被弃用和ConnectivityManager.TYPE_WIFI
弃用
这是我检查当前网络是否在最新的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
}
}
(几乎)所有答案均已在Android P中弃用,因此这里是C#
解决方案(对于Java开发人员来说很容易遵循)
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);
}
这里的关键是 Android.Net.TransportType
我们可能需要多次检查互联网连接。因此,如果我们使用的扩展方法编写代码块,对我们来说将更加容易Context
。下面是Context
和的辅助扩展Fragment
。
检查互联网连接
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
}
在android M(API 28)以下未找到ConnectivityManager.getActiveNetwork()。在Android L上方不推荐使用networkInfo.getState()。
因此,最终答案是:
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;
}
许多答案仍然使用低于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;
}
..
并且,不要忘记在清单中添加此行
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
由于发布的答案仅允许您查询活动网络,因此以下是获取NetworkInfo
任何网络的方法,不仅适用于活动网络(例如Wifi网络)(对不起,前面的Kotlin代码)
(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
cm.getNetworkCapabilities(cm.activeNetwork).hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
您可以使用NetManager在带有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) }
}
}
https://www.agnosticdev.com/content/how-detect-network-connectivity-android
请按照本教程进行操作,它可以帮助任何寻求答案的人。
注意networkInfo已被弃用,因此在将getApplicationContext()作为参数传递给@vidha答案后,将其替换为isNetworkReacheable()
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 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();
}
}
这在Kotlin对我有用。Network Manager类中不推荐使用许多API,因此下面的答案涵盖了所有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。(Kotlin)
但是,仅在API 29中弃用了getActiveNetworkInfo(),并且只能在所有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
}
像这样:
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
}