如何验证连接的Wifi网络的密码正确

时间:2018-11-05 11:21:37

标签: android android-wifi wifimanager

当用户连接到Wi-Fi网络时,我需要验证用户在我的应用中输入的密码是否正确。为了验证用户当时知道他所连接的网络的密码。

当我尝试连接到网络时,我遇到的问题是wifiManager.addNetwork(conf)始终返回-1(即使您第一次断开与网络的连接),因为系统中已经存在该网络。因此,如果用户输入的密码正确或错误,则尝试连接代码时的行为相同。

理想的解决方案是在连接之前删除网络配置,但这不能从Android 6.0中完成。

这是我用来测试的代码:

public void connectFailPassword()
{
    connect("AAAAAAAA", "fail password");
}


public void connectOkPassword()
{
    connect("12345678", "OK password");
}

private void connect(String password, String from) {

    String networkSSID = "MY SSID TO TEST HERE";


    WifiConfiguration conf = new WifiConfiguration();


    conf.SSID = "\"" + networkSSID + "\"";
    conf.preSharedKey = "\"" + password + "\"";

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int netId = wifiManager.addNetwork(conf);
    Log.i("TAG",  from + " WifiConnector.connect.id " + netId);

    registerWiFiEventsReceiver();
    //wifiManager.disconnect();
    Boolean enabled = wifiManager.enableNetwork(netId, true);
    Log.i("TAG", from + " WifiConnector.enabled " + enabled);

    //wifiManager.reconnect();



}


private void registerWiFiEventsReceiver() {

    IntentFilter mFilter = new IntentFilter();
    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    mFilter.addAction(  WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);


    ((Activity) context).registerReceiver(receiver, mFilter);

}


private BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {


        Log.i("TAG", "WifiConnector.receiver: " + getCurrentNetId() + " intent: " + intent.getExtras().toString());


    }

};

使用确定的密码连接:

I/TAG: OK password WifiConnector.connect.id -1
I/TAG: OK password WifiConnector.enabled false
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=368]
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=1432]
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=92]
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=128]

使用错误的密码连接:

I/TAG: fail password WifiConnector.connect.id -1
I/TAG: fail password WifiConnector.enabled false
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=368]
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=1432]
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=92]
I/TAG: WifiConnector.receiver: 88 intent: Bundle[mParcelledData.dataSize=128]

我知道这是可以做到的,因为当您在所有设备(甚至高于6.0)中添加wifi热点时,instantbridge应用程序便会做到这一点。

0 个答案:

没有答案