我在以太网连接方面遇到一些问题,尤其是NetworkInfo类始终返回null。

我实际上正在使用此代码:

ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); //not null
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);  //null
        return networkInfo != null && networkInfo.isConnected();


我正在尝试建立以太网连接,有人可以帮助我吗?
提前致谢!

最佳答案

对于以太网,请尝试如下

public Boolean isEthernetConnected(){
    if(isNetworkAvailable()){
        ConnectivityManager cm
        = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return (cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET);
    }
    return false;
}

 private Boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

关于java - NetworkInfo返回始终为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58236826/

10-12 02:39