使用compileSdkVersion 23,但是尝试支持9。
getNetworkInfo(int)在23中已弃用。建议改为使用getAllNetworks和getNetworkInfo(Network)。但是,这两者都需要最低限度的API 21。
我们可以在支持包中使用哪个类可以帮助解决这个问题吗?
我知道提出了一个解决方案before,但是我对9的最低api要求的挑战造成了问题。
答案 0 :(得分:140)
您可以使用:
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
}
答案 1 :(得分:15)
更新回答(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或移动互联网从应用程序的任何部分连接到Internet。
答案 2 :(得分:13)
至2018年10月,已接受的答案已弃用。
getType()
及其类型本身现已在API级别28中弃用。来自Javadoc:
呼叫者应改用使用NetworkCapabilities#TRANSPORT *常量之一来检查NetworkCapabilities#hasTransport
要使用NetworkCapabilities
,您需要将Network
实例传递给getNetworkCapabilities()
方法。要获取该实例,您需要调用API级别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
,您可以找到here。
重要说明::如果您已连接到Wi-Fi 和到VPN,则当前状态可能是TRANSPORT_VPN
,因此您可能想要也检查一下。
请不要忘记为您的AndroidManifest文件添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 3 :(得分:10)
在28 (Android P)
中不再推荐使用的答案,但是其替换方法仅适用于23 (Android M)
。为了支持较旧的设备,我编写了一个辅助函数。
使用方法:
int type = getConnectionType(getApplicationContext());
它返回一个int
,您可以在代码中将其更改为enum
:
0:没有可用的互联网(可能是在飞行模式下,或者正在加入wi-fi)。
1:蜂窝(移动数据,3G / 4G / LTE等等)。
2:Wi-fi。
您可以复制辅助功能的Kotlin或Java版本。
科特琳:
@IntRange(from = 0, to = 2)
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 {
cm?.run {
cm.activeNetworkInfo?.run {
if (type == ConnectivityManager.TYPE_WIFI) {
result = 2
} else if (type == ConnectivityManager.TYPE_MOBILE) {
result = 1
}
}
}
}
return result
}
Java:
@IntRange(from = 0, to = 2)
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 (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;
}
}
}
}
return result;
}
答案 4 :(得分:4)
许多答案仍然使用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" />
答案 5 :(得分:3)
如芝士面包所示,请使用 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;
}
现在调用方法,为了安全使用try 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" />
答案 6 :(得分:3)
这可以帮助某人 科特林
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
}
答案 7 :(得分:3)
要检查您是否在线:
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" />
答案 8 :(得分:2)
为了安全起见,我建议也使用方法
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;
}
}
答案 9 :(得分:2)
科特林版本:
fun isInternetOn(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
val activeNetwork = cm?.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}
答案 10 :(得分:1)
以下代码适用于所有API。(科特琳)
但是,仅在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
}
答案 11 :(得分:1)
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) }
}
}
答案 12 :(得分:1)
检查可用的互联网
@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
}
答案 13 :(得分:1)
我们可能需要多次检查互联网连接。因此,如果我们以Context
的扩展方法编写代码块,对我们来说将更加容易。以下是我对Context
和Fragment
的帮助扩展。
检查Internet连接
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)
答案 14 :(得分:1)
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;
}
答案 15 :(得分:1)
类似这样的东西:
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();
答案 16 :(得分:1)
这也将在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
}
答案 17 :(得分:1)
版本28中弃用了可接受的答案,因此这是我在项目中使用的解决方案。
返回连接类型。 false:没有Internet连接;真实:移动 数据|| wifi
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;
}
答案 18 :(得分:0)
使用 目标sdk 29 检查网络状态:
process_event_b
答案 19 :(得分:0)
这在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" />
答案 20 :(得分:0)
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;
}
答案 21 :(得分:0)
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();
}
}
答案 22 :(得分:0)
最好检查您的网络是否连接到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
}
答案 23 :(得分:0)
(几乎)所有答案均已在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
答案 24 :(得分:0)
这是我检查当前网络是否在最新的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
}
}
答案 25 :(得分:0)
由于发布的答案仅允许您查询活动的网络,因此以下说明如何获取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