使用compileSdkVersion 23,但是尝试支持9到9。
getNetworkInfo(int)在23中已弃用。建议改为使用getAllNetworks和getNetworkInfo(Network)。然而,这两者都需要最少的API 21。
我们可以在支持包中使用哪个类可以帮助解决这个问题吗?
我知道before提出了一个解决方案,但是我对9的最低api要求的挑战造成了问题。
您可以使用:
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
}
最好检查您的网络是否连接到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
}
检查互联网
@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
}
我们可能需要多次检查互联网连接。因此,如果我们在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)
由于发布的答案只允许您查询活动网络,这里是如何为任何网络获取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
以下是我在最新的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
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();
}
}
至于2018年10月,已接受的答案已被弃用。
getType()
和类型本身现已在API Level 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" />
更新回答(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。
接受的答案在28 (Android P)
中再次被弃用,但其替换方法仅适用于23 (Android M)
。为了支持旧设备,我编写了一个辅助函数。
如何使用:
int type = getConnectionType(getApplicationContext());
它返回一个int
,您可以在代码中将其更改为enum
:
0:没有互联网可用(可能在飞机模式下,或在加入Wi-Fi的过程中)。
1:移动电话(移动数据,3G / 4G / LTE等)。
答:在。
您可以复制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;
}
正如Cheese Bread建议的那样,使用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" />
要检查您是否在线:
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之前/之后的互联网连接类型
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" />
为了安全起见,我建议也使用方法
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;
}
}
Kotlin版本:
fun isInternetOn(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
val activeNetwork = cm?.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}
接受的答案在版本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;
}