在2个Wifi网络之间切换,连接失败

时间:2017-04-11 09:36:52

标签: java android ftp wifi android-things

我无法在运行Android的Raspberry Pi 3上以编程方式在两个网络之间切换(但它应该与运行普通Android相同)。

第一个网络来自设备服务器作为接入点。它运行一个FTP服务器,我需要通过它的网络访问。它在我知道的192.168.xxx.xxx网络中有一个静态IP地址,并由WPA2-PSK保护。我有SSID和密码,我知道这是正确的。该设备位于其自己的专用网络中,使其自身无法访问外部地址。连接到它的唯一方法是连接到它的网络和FTP到它的静态地址。

第二个网络是一个开放的网络,我也知道SSID。这个是由另一个应用程序预先配置的,因此我的应用程序无法更新配置。

以下代码就是我目前的代码。 DownloadFilesTask在我的开始屏幕的onCreate中调用。

第一个网络的配置似乎失败,因为将配置添加到WifiManager会返回-1作为networkId,因为我可以在断开连接并丢失所有日志记录之前在最后两行的日志中看到。这两行是:

04-11 11:10:51.258 1332-1349 / rocks.androidthings.hellothings D /连接:SSID1 passphase

04-11 11:10:51.259 411-740 / system_process I / addOrUpdateNetwork:uid = 10026 SSID SSID1 nid = -1

在此之后,我得到一个java.net.socketException:无效参数或无法连接分配请求的地址。

过去几天我一直在努力解决这个问题,所以任何帮助都会受到赞赏。

public String connectToNetwork1() {
    try {
        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (!wifiManager.getConnectionInfo().getSSID().equals("\"" + SSID1 + "\"")) {

            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + SSID1 + "\"";

            conf.preSharedKey = "\"" + passphrase + "\"";
            conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); // For WPA2
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            Log.d("connecting", conf.SSID + " " + conf.preSharedKey);

            int networkId = wifiManager.addNetwork(conf);

            Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);
            wifiManager.disconnect();
            Thread t = new Thread(() -> {
                wifiManager.enableNetwork(networkId, true);                 
            });
            t.start();
            t.join();
            wifiManager.reconnect();
            Log.d("re connecting", wifiManager.getConnectionInfo().getSSID());
            return wifiManager.getConnectionInfo().toString();
        } else {
            Log.d("WIFI", "already connected to network1");
            return "already connected to network1";
        }
    } catch (Exception ex) {
        Log.d("ERROR", ex.toString());
    }
    return "nougabollen";
}

public String connectToNetwork2() {
    try {
        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.getConnectionInfo().getSSID().equals("\"" + SSID2 + "\"")) {

            /*WifiConfiguration conf = new WifiConfiguration();             //
            conf.SSID = "\"" + SSID2 + "\"";                                //
                                                                            //  
            conf.status = WifiConfiguration.Status.ENABLED;                 //
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  // this block is useless since my application can't update this network
                                                                            // since network 2 is configured elsewhere  
            Log.d("connecting", conf.SSID);                                 //
                                                                            //
            int networkId = wifiManager.addNetwork(conf);*/                 //
            int networkId = -2;
            List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
            for(WifiConfiguration wc : configs){
                if(wc.SSID.equals("\"" + SSID2 + "\"")){
                    networkId = wc.networkId;
                }
            }
            int finalNetworkId = networkId;
            wifiManager.disconnect();
            Thread t = new Thread(() -> {
                wifiManager.enableNetwork(finalNetworkId, true);
            });
            t.start();
            t.join();
            wifiManager.reconnect();
            Log.d("re connecting", wifiManager.getConnectionInfo().getSSID());
            return  "tried networkId: " + networkId + "   " + wifiManager.getConnectionInfo().toString();
        } else {
            Log.d("WIFI", "already connected to network2");
            return "already connected to network2";
        }
    } catch (Exception ex) {
        Log.d("ERROR", ex.toString());
    }
    return "smoutebollen";
}

private class DownloadFilesTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String text = "";
        text += " " + connectToNetwork1();
        text += " " + retrieveFile();
        text += " " + connectToNetwork2();
        Log.d("text", text);
        return text;
    }

    protected void onPostExecute(String text) {
        test.setText(text);
    }
}

我用来检索文件的代码是(使用apache.commons.net):

public static String getDummyFile(){
    FTPClient client = new FTPClient();
    Log.d("ftp","client created");
    InetAddress ip = null;
    try {
        ip = InetAddress.getByName("192.168.242.129"); // this is the address of the device creating the first network
    }
    catch (Exception e){
        Log.d("inetaddres",e.toString());
    }
    try {
        Log.d("inet", ip.getHostAddress());
        int reply = -1; //response


        client.connect(ip);
        Log.d("ftp","client connected");
        reply = client.getReplyCode();
        Log.d("ftp",""+reply);
        client.enterLocalPassiveMode();
        Log.d("ftp","passive mode");

        //check if login is accepted
        /*if (!client.login("anonymous", "")) {
            Log.d("FTP", "error logging in");
        }*/

        //check if bad reponse code
        /*if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            Log.d("FTP", "connection refused");
        }*/

        //set file type to binary and enter passive mode, active not supported on android
        client.setFileType(FTP.BINARY_FILE_TYPE);
        Log.d("ftp", "set type to binary");
        client.changeWorkingDirectory("/files");
        Log.d("ftp","changed dir");
        String[] names = client.listNames();
        Log.d("FTP", names[1].toString());
        Log.d("FTP", client.printWorkingDirectory() + "/" + names[1].toString());
        mapFiles(client,"/files","",0);
        return client.printWorkingDirectory() + "/" + names[1].toString();

    } catch (Exception e) {
        Log.d("ftp",e.toString());
        text = e.toString();
    }
    finally {
        try {
            client.disconnect();
        }
        catch (Exception e){

        }
    }
    return text;
}

在尝试连接时给出了异常,因为我没有连接到网络。

1 个答案:

答案 0 :(得分:0)

所以我设法让它工作,以下是我的工作代码。主要区别在于将WPA设置为协议,并且在启用网络后让线程连接睡眠3秒钟。

    public String connectToXs() {
    try {
        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        if (!wifiManager.getConnectionInfo().getSSID().equals("\"ssid\"")) {

            WifiConfiguration wc = new WifiConfiguration();
            wc.SSID = "\"ssid\"";

            wc.preSharedKey  = "\"key\"";
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            int res = wifiManager.addNetwork(wc);
            Log.d("WifiPreference", "add Network returned " + res );
            final boolean[] b = new boolean[1];
            Thread t = new Thread(() -> {
                b[0] = wifiManager.enableNetwork(res, true);
                wifiManager.setWifiEnabled(true);
                try {
                    Thread.sleep(3000);
                }
                catch (Exception e){
                    Log.d("ERROR",e.toString());
                }
            });
            t.start();
            t.join();
            Log.d("WifiPreference", "enableNetwork returned " + b[0]);

            return wifiManager.getConnectionInfo().toString();
        } else {
            Log.d("WIFI", "already connected");
            return "already connected";
        }
    } catch (Exception ex) {
        Log.d("ERROR", ex.toString());
    }
    return "nougabollen";
}

public String connectToGuest() {
    try {
        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.getConnectionInfo().getSSID().equals("\"" + "ssid2" + "\"")) {

            //int networkId = wifiManager.addNetwork(conf);
            int networkId = -2;
            List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
            for(WifiConfiguration wc : configs){
                if(wc.SSID.equals("\"SSID2\"")){
                    networkId = wc.networkId;
                }
            }
            int finalNetworkId = networkId;
            wifiManager.disconnect();
            Thread t = new Thread(() -> {
                wifiManager.enableNetwork(finalNetworkId, true);
                try {
                    Thread.sleep(3000);
                }
                catch (Exception e){
                    Log.d("ERROR",e.toString());
                }
            });
            t.start();
            t.join();
            wifiManager.reconnect();
            Log.d("re connecting", wifiManager.getConnectionInfo().getSSID());
            return  "tried networkId: " + networkId + "   " + wifiManager.getConnectionInfo().toString();
        } else {
            Log.d("WIFI", "already connected");
            return "already connected";
        }
    } catch (Exception ex) {
        Log.d("ERROR", ex.toString());
    }
    return "smoutebollen";
}