web-dev-qa-db-ja.com

AndroidプログラムによるWiFi接続

私のAndroidアプリケーションでパスワードを送信してwifi接続を確立する方法を知っていますか?

11
Mustafa İrer

SSIDとそのパスワードを次のメソッドに渡します。

public void connectToAP(String ssid, String passkey) {
    Log.i(TAG, "* connectToAP");

    WifiConfiguration wifiConfiguration = new WifiConfiguration();

    String networkSSID = ssid;
    String networkPass = passkey;

    Log.d(TAG, "# password " + networkPass);

    for (ScanResult result : scanResultList) {
        if (result.SSID.equals(networkSSID)) {

            String securityMode = getScanResultSecurity(result);

            if (securityMode.equalsIgnoreCase("OPEN")) {

                wifiConfiguration.SSID = "\"" + networkSSID + "\"";
                wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                int res = wifiManager.addNetwork(wifiConfiguration);
                Log.d(TAG, "# add Network returned " + res);

                boolean b = wifiManager.enableNetwork(res, true);
                Log.d(TAG, "# enableNetwork returned " + b);

                wifiManager.setWifiEnabled(true);

            } else if (securityMode.equalsIgnoreCase("WEP")) {

                wifiConfiguration.SSID = "\"" + networkSSID + "\"";
                wifiConfiguration.wepKeys[0] = "\"" + networkPass + "\"";
                wifiConfiguration.wepTxKeyIndex = 0;
                wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                int res = wifiManager.addNetwork(wifiConfiguration);
                Log.d(TAG, "### 1 ### add Network returned " + res);

                boolean b = wifiManager.enableNetwork(res, true);
                Log.d(TAG, "# enableNetwork returned " + b);

                wifiManager.setWifiEnabled(true);
            }

            wifiConfiguration.SSID = "\"" + networkSSID + "\"";
            wifiConfiguration.preSharedKey = "\"" + networkPass + "\"";
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            int res = wifiManager.addNetwork(wifiConfiguration);
            Log.d(TAG, "### 2 ### add Network returned " + res);

            wifiManager.enableNetwork(res, true);

            boolean changeHappen = wifiManager.saveConfiguration();

            if(res != -1 && changeHappen){
                Log.d(TAG, "### Change happen");

                AppStaticVar.connectedSsidName = networkSSID;

            }else{
                Log.d(TAG, "*** Change NOT happen");
            }

            wifiManager.setWifiEnabled(true);
        }
    }
}

public String getScanResultSecurity(ScanResult scanResult) {
    Log.i(TAG, "* getScanResultSecurity");

    final String cap = scanResult.capabilities;
    final String[] securityModes = { "WEP", "PSK", "EAP" };

    for (int i = securityModes.length - 1; i >= 0; i--) {
        if (cap.contains(securityModes[i])) {
            return securityModes[i];
        }
    }

    return "OPEN";
}

マニフェストファイルに必要な権限を追加することを忘れないでください。

31
AnujAroshA

100%動作します。

このようにして、特定のWifiに接続できます。MainActivity.Javaのこのコード

////////////// >>> Wifi接続(WP2)<<< ////////////////

        WifiConfiguration wifiConfig = new WifiConfiguration();

        wifiConfig.SSID = String.format("\"%s\"", "Wifi name");
        wifiConfig.preSharedKey = String.format("\"%s\"", "Wifi password");

        WifiManager wifiManager=(WifiManager)getSystemService(WIFI_SERVICE);
        int netId = wifiManager.addNetwork(wifiConfig);
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();

また、このコードをAndroidManifest.xmlに含めることを忘れないでください

<uses-permission Android:name="Android.permission.ACCESS_WIFI_STATE" />
<uses-permission Android:name="Android.permission.CHANGE_WIFI_STATE" />
<uses-permission Android:name="Android.permission.ACCESS_NETWORK_STATE" />
<uses-permission Android:name="Android.permission.INTERNET" />
6
Kamran Gasimov

AnujAroshA ここから投稿されたコードは本当に役に立ちます。しかし、欠落している他のケースがあります:

  ..
  } else if (securityMode.equalsIgnoreCase("PSK")) {
    // PSK code
  ..

それ以外の場合、PSKコードはWEPおよびOPENネットワークに対しても実行されます。

そして、私の意見では、コードスタイルは最適ではありません。 2つの文字列networkSSIDとnetworkPassを作成する必要はありません。 ssidまたはpasskeyを使用するだけです。

提案:wifi構成と接続方法の作成を分割します。

(1)WifiConfigurationを作成する方法:

private WifiConfiguration createAPConfiguration(String networkSSID, String networkPasskey, String securityMode) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();

        wifiConfiguration.SSID = "\"" + networkSSID + "\"";

        if (securityMode.equalsIgnoreCase("OPEN")) {

            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        } else if (securityMode.equalsIgnoreCase("WEP")) {

            wifiConfiguration.wepKeys[0] = "\"" + networkPasskey + "\"";
            wifiConfiguration.wepTxKeyIndex = 0;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

        } else if (securityMode.equalsIgnoreCase("PSK")) {

            wifiConfiguration.preSharedKey = "\"" + networkPasskey + "\"";
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

        } else {
            Log.i(TAG, "# Unsupported security mode: "+securityMode);

            return null;
        }

        return wifiConfiguration;

    }

(2)AP接続の方法:

    public int connectToAP(String networkSSID, String networkPasskey) {
    for (ScanResult result : scanResultList) {

        if (result.SSID.equals(networkSSID)) {

            String securityMode = getScanResultSecurity(result);

            WifiConfiguration wifiConfiguration = createAPConfiguration(networkSSID, networkPasskey, securityMode);

            int res = wifiManager.addNetwork(wifiConfiguration);
            Log.d(TAG, "# addNetwork returned " + res);

            boolean b = wifiManager.enableNetwork(res, true);
            Log.d(TAG, "# enableNetwork returned " + b);

            wifiManager.setWifiEnabled(true);

            boolean changeHappen = wifiManager.saveConfiguration();

            if (res != -1 && changeHappen) {
                Log.d(TAG, "# Change happen");
                connectedSsidName = networkSSID;
            } else {
                Log.d(TAG, "# Change NOT happen");
            }

            return res;
        }
    }

    return -1;
}

(3)投稿されたスキャン方法100% AnujAroshA

public String getScanResultSecurity(ScanResult scanResult) {

    final String cap = scanResult.capabilities;
    final String[] securityModes = { "WEP", "PSK", "EAP" };

    for (int i = securityModes.length - 1; i >= 0; i--) {
        if (cap.contains(securityModes[i])) {
            return securityModes[i];
        }
    }

    return "OPEN";
}
3
Timo Bähr

Ssidとパスワードを教えてください

    fun connectToWifi(ssid: String, password: String) {
    val connManager = context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
    val wifiConfiguration = WifiConfiguration()
    wifiConfiguration.SSID = String.format("\"%s\"", ssid)
    wifiConfiguration.preSharedKey = String.format("\"%s\"", password)
    wifiManager = context!!.getSystemService(Context.WIFI_SERVICE) as WifiManager
    val netId: Int = wifiManager.addNetwork(wifiConfiguration)
    wifiManager.disconnect()
    wifiManager.enableNetwork(netId, true)
    wifiManager.reconnect()
    val config = WifiConfiguration()
    config.SSID == "\"\"" + ssid + "\"\""
    config.preSharedKey == "\"\"" + password + "\"\""
    wifiManager.addNetwork(config)
}
0
RanaUmer