如何使用相同的应用程序跨两个Android设备交换数据?

时间:2017-12-14 10:06:05

标签: android android-studio

我有以下代码连接到另一部手机的热点wifi。

这个想法是让两个设备互相发送简单的数据;在每一端,手机都连接到我的应用程序。然后应用程序响应发送的数据。

    private void ConnectWifi(String networkSSID, String networkPass) {

    List<ScanResult> scanResult = wifiManager.getScanResults();
    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + networkSSID + "\"";
    String lstItems = new String();
    for (ScanResult scanResults : scanResult) {

        lstItems += "\n" + scanResults.SSID;

        if (scanResults.capabilities.contains("WEP")) {
            conf.wepKeys[0] = "\"" + networkPass + "\"";
            conf.wepTxKeyIndex = 0;
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        } else if (scanResults.capabilities.contains("WPA")) {
            conf.preSharedKey = "\"" + networkPass + "\"";
        } else {
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }

    }


    wifiManager.addNetwork(conf);


    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("KEBWARO 3")) {
            wifiManager.disconnect();

            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();
            //subscriberData.setNetworkID(i.SSID);
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setIcon(R.drawable.beer);
            alert.setTitle("CONNECTED SUCCESSFULLY");
            alert.setMessage("CONNECTED TO " + i.SSID);
            alert.show();
            networkID = i.SSID;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

必须通过Android API 14 +中的Wifi P2P - Wifi Direct网络发现API完成。

您可以在此处找到示例代码

https://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html