无法访问是 网络支持 在 android ConnectivityManager 类中



我正在尝试使用isNetworkSupported(int networkType)来检查硬件是否支持仅wifi模式。但它给出的错误是"该方法是网络支持的(int)未定义类型ConnectivityManager的类型

以下是我的代码:

 ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
 boolean checkStatus =  cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE);

请告诉我我们如何在我们的活动中访问这个isNetworkSupported方法。

谢谢。

根据documentisNetworkSupported不是类ConnectivityManager的方法。

如果您想检查互联网连接状态,请检查此

ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                  activeNetwork.isConnectedOrConnecting();

但是我能够在 https://android.googlesource.com/platform/frameworks/base.git/+/android-4.3_r2.1/core/java/android/net/ConnectivityManager.java 中看到这种方法,在 android 工作室中它也显示了这种方法。

谢谢大家!

经过一些研究并与我的同事一起帮助我使用 java 反射来解决这个问题如下。

ConnectivityManager cm = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> cmlClass = cm.getClass();
String status = "";
try { 
    final Method wifiCheckMethod = cmlClass.getMethod("isNetworkSupported", int.class);
    boolean hasMobileNetwork = (Boolean) wifiCheckMethod.invoke(cm, ConnectivityManager.TYPE_MOBILE);
    status = hasMobileNetwork ? "This device has mobile support model" : "This is wifi only model";
    Log.i(getClass().getSimpleName(), "The network status is..."+hasMobileNetwork);
} catch (Exception ex) {
    ex.printStackTrace();
    status = "Error while getting device support model";
}
Toast.makeText(MainActivity.this, "Network support message.."+status, Toast.LENGTH_SHORT).show();

最新更新