簡體   English   中英

Android Wifi Manager無法正確連接

[英]Android Wifi Manager not connecting properly

我設法制作了一個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();
                }

嘗試這個:

  • 在“ onResume”中處理NDEF消息,然后
  • 啟用wifi時添加wifi

換句話說,如果未啟用wifi,

  • 存儲wifi憑據,
  • 收聽Wifi廣播,直到啟用,然后
  • 添加網絡

另外,您的NDEF解析是一個真正的技巧。 嘗試使用此方法進行解析是否可行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM