简体   繁体   English

Android Wifi Manager无法正确连接

[英]Android Wifi Manager not connecting properly

I've managed to make a NFC application in which when the specific tag is scanned, the phone will automatically establish connection with one particular Wi-Fi. 我设法制作了一个NFC应用程序,在其中扫描特定标签时,手机将自动与一个特定的Wi-Fi建立连接。 (even if Wi-Fi is off) I've already included the SSID and password in the code(tag) so the users can just scan the tag to connect. (即使Wi-Fi已关闭)我已经在代码(标签)中包含了SSID和密码,因此用户只需扫描标签即可连接。 However, I notice that on my first tap, Wi-Fi is enabled(if disabled) but it will not connect to the Wi-Fi. 但是,我注意到,第一次点击时,启用了Wi-Fi(如果已禁用),但它无法连接到Wi-Fi。 Only on the second tap, it connects to the specified Wi-Fi. 仅在第二次点击时,它才连接到指定的Wi-Fi。 Why is it so? 为什么会这样呢?

My code: 我的代码:

    @Override
    protected void onNewIntent(Intent intent) {

        String result2="";
        String resultid="";
        String resultpw="";

        super.onNewIntent(intent);      
        SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
        int storedPreference = preferences.getInt("storedInt", 0);

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            NdefMessage[] messages = null;
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawMsgs != null) {
                messages = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    messages[i] = (NdefMessage) rawMsgs[i];
                }
            }
            if(messages[0] != null) {
                /*
                String result="";
                byte[] payload = messages[0].getRecords()[0].getPayload();
                // this assumes that we get back am SOH followed by host/code
                for (int b = 0; b<payload.length; b++) { // skip SOH
                    result += (char) payload[b];
                }
                */


                try{
                //grabbing 2nd payload

                byte[] payload2 = messages[0].getRecords()[1].getPayload();
                for (int test = 0; test<payload2.length; test++) { // skip SOH
                    result2 += (char) payload2[test];
                    //Toast.makeText(this,result2,Toast.LENGTH_SHORT).show();  
                    }
                }
                catch(ArrayIndexOutOfBoundsException e){
                    Toast.makeText(getApplicationContext(), "Wrong tag detected. Try again!", Toast.LENGTH_SHORT).show();
                }

                //grab ssid
                try{

                    byte[] payload3 = messages[0].getRecords()[2].getPayload();
                    for (int test = 0; test<payload3.length; test++) { // skip SOH
                        resultid += (char) payload3[test];
                        //Toast.makeText(this,result2,Toast.LENGTH_SHORT).show();  
                        }
                    }
                    catch(ArrayIndexOutOfBoundsException e){

                    }

                //grab ssid_pw
                try{


                    byte[] payload4 = messages[0].getRecords()[3].getPayload();
                    for (int test = 0; test<payload4.length; test++) { // skip SOH
                        resultpw += (char) payload4[test];
                        //Toast.makeText(this,result2,Toast.LENGTH_SHORT).show();  
                        }
                    }
                    catch(ArrayIndexOutOfBoundsException e){

                    }   



                if (result2.contains("StarbucksBestCoffee"))
                    {
                    final ImageView img = (ImageView)findViewById(R.id.imageView1);

                    /* Call to convert bytes to hex .
                     * 
                    String uid = toHex(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
                      Toast.makeText(this, uid, Toast.LENGTH_LONG).show();*/



                    /*if (storedPreference!=10)
                    {
                        Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
                        storedPreference++;
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putInt("storedInt", storedPreference);
                        img.setImageResource(images[storedPreference]);
                        img.invalidate();
                    }*/
                        if (storedPreference==10)
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            builder.setCancelable(false);
                            builder.setTitle("Redeem Your Coupon?");
                            builder.setInverseBackgroundForced(true);
                            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    dialog.dismiss();
                                    SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();
                                    editor.putInt("storedInt", 0); // value to store
                                    editor.commit();    
                                    img.setImageResource(images[0]);
                                    img.invalidate();
                                }
                            });
                            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    img.setImageResource(images[10]);
                                    img.invalidate();
                                }
                            });
                            builder.show();
                        }
                    else
                    {
                        Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
                        storedPreference++;
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putInt("storedInt", storedPreference);
                        editor.commit();
                        img.setImageResource(images[storedPreference]);
                        img.invalidate();
                    }
                        if (resultid!=null&&resultpw!=null)
                        {
                         //Wi-Fi Manager auto-connect

                         WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                         WifiConfiguration wc = new WifiConfiguration();
                         wc.SSID = "\"" + resultid + "\"";
                         wc.preSharedKey  = "\"" + resultpw + "\"";
                         wc.hiddenSSID = true;
                         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);
                         int res = wifi.addNetwork(wc);
                         Log.d("WifiPreference", "add Network returned " + res );
                         boolean b = wifi.enableNetwork(res, true);        
                         Log.d("WifiPreference", "enableNetwork returned " + b );
                         wifi.setWifiEnabled(true);
                        }

                    }
                else 
                {
                    Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
                }

Try this: 尝试这个:

  • Process the NDEF message in 'onResume', and 在“ onResume”中处理NDEF消息,然后
  • Add the Wifi when wifi is enabled 启用wifi时添加wifi

In other words, if wifi is not enabled, 换句话说,如果未启用wifi,

  • Store the wifi credentials, 存储wifi凭据,
  • Listen for Wifi broadcasts untill enabled, then 收听Wifi广播,直到启用,然后
  • Add the network 添加网络

Also, your NDEF parsing is a real hack. 另外,您的NDEF解析是一个真正的技巧。 Try if parsing using this works instead. 尝试使用此方法进行解析是否可行。

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

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