是否可以检测Android设备是否已连接到路由器?

时间:2016-03-21 01:50:04

标签: java android android-networking

以下代码可用于检查以太网连接:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState() == NetworkInfo.State.CONNECTED)
{
...
}

如果已连接,则至少有两种可能性:

  1. 连接到路由器。
  2. 它连接到另一个设备(即点对点连接)
  3. 我如何区分彼此?

1 个答案:

答案 0 :(得分:-1)

代码如下:

public static int getNetWorkType(Context context) {  

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();  

    if (networkInfo != null && networkInfo.isConnected()) {  
        String type = networkInfo.getTypeName();  

        if (type.equalsIgnoreCase("WIFI")) {  
            mNetWorkType = NETWORKTYPE_WIFI;  
        } else if (type.equalsIgnoreCase("MOBILE")) {  
            String proxyHost = android.net.Proxy.getDefaultHost();  

            mNetWorkType = TextUtils.isEmpty(proxyHost)  
                    ? (isFastMobileNetwork(context) ? NETWORKTYPE_3G : NETWORKTYPE_2G)  
                    : NETWORKTYPE_WAP;  
        }  
    } else {  
        mNetWorkType = NETWORKTYPE_INVALID;  
    }  

    return mNetWorkType;  
}   

注意:热点也是wifi