简体   繁体   English

如何在Android中切换主机

[英]How to switch hosts in Android

I'm trying to access ESP8266 over internet and from LAN, and i'm using no-ip to get connected over internet but if i have no internet connection i can not access ESP8266 so i have to connect to LAN if there is no internet connection. 我正在尝试通过Internet和LAN来访问ESP8266,并且我正在使用No-ip通过Internet进行连接,但是如果我没有Internet连接,那么我将无法访问ESP8266,所以如果没有Internet,我必须连接到LAN连接。 I read forums here and almost tried all but unable to access ESP8266 through LAN. 我在这里阅读论坛,几乎尝试了所有但无法通过LAN访问ESP8266的问题。

String address = "mynoipdomain"; //global variable
String lan = "myesplocalip"; // global variable

String serverAdress;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    assert connectivityManager != null; //i added this line because Android Studio was giving warning that "Method invocation 'getNetworkInfo' may produce 'java.lang.NullPointerException'"
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        serverAdress = address + ":3001"; //3001 is port
    }
    else{
        serverAdress = lan + ":3001";
    }

the if condition probably should be: if条件可能应该是:

String bssid = getCurrentSsid(getContext());

if(bssid != null && bssid.equals("HOME_BSSID")) {
    serverAdress = lan + ":3001";
} else if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED) {
    serverAdress = address + ":3001";
} else {
    // both networks are offline
}

combined with this method ( source ): 结合此方法( ):

public String getCurrentSsid(Context context) {
    String ssid = null;
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo == null) {
        return null;
    }

    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) {
            ssid = connectionInfo.getSSID();
        }
    }
    return ssid;
}

in order to prefer the local IP, when the home WiFi is connected. 为了更喜欢本地IP,在连接家庭WiFi时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM