要检查Android设备上的连接是否具有互联网连接,可以使用ConnectivityManager类的getActiveNetworkInfo()方法。以下是一个示例代码,演示如何进行此检查:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class InternetConnectionChecker {
private Context context;
public InternetConnectionChecker(Context context) {
this.context = context;
}
public boolean isInternetConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
// 检查网络连接是否可用
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
// 检查连接是否具有互联网连接
return activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI || activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
return false;
}
}
在上述代码中,我们创建了一个名为InternetConnectionChecker的类,该类接受一个Context对象作为构造函数参数。然后,我们使用传入的Context对象获取ConnectivityManager的实例。接下来,我们使用getActiveNetworkInfo()方法获取当前活动的网络连接信息。最后,我们检查网络连接是否可用,并检查连接类型是否为WiFi或移动网络,以判断是否具有互联网连接。
要使用上述代码示例,您可以在您的Activity或Fragment中创建InternetConnectionChecker对象,并调用isInternetConnected()方法来检查互联网连接:
InternetConnectionChecker internetConnectionChecker = new InternetConnectionChecker(this); // “this”是指当前Activity或Fragment的Context
boolean isInternetConnected = internetConnectionChecker.isInternetConnected();
if (isInternetConnected) {
// 有互联网连接
} else {
// 没有互联网连接
}
请确保在使用上述代码之前添加相应的权限到您的AndroidManifest.xml文件中: