Android Wifi Manager无法正常连接

时间:2012-12-13 14:38:36

标签: java android wifi nfc

我设法制作了一个NFC应用程序,当扫描特定标签时,手机将自动与一个特定的Wi-Fi建立连接。 (即使Wi-Fi已关闭)我已经在代码(标签)中包含了SSID和密码,因此用户只需扫描标签即可进行连接。但是,我注意到在我第一次点击时,启用了Wi-Fi(如果已禁用),但它无法连接到Wi-Fi。只有在第二次点击时,它才会连接到指定的Wi-Fi。为什么会这样?

我的代码:

    @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();
                }

1 个答案:

答案 0 :(得分:0)

试试这个:

  • 在'onResume'和
  • 中处理NDEF消息
  • 启用wifi时添加Wifi

换句话说,如果没有启用wifi,

  • 存储wifi凭据,
  • 收听Wifi广播直到启用,然后
  • 添加网络

此外,您的NDEF解析是一个真正的黑客。如果使用this进行解析,请尝试使用。