0

我正在使用一个教程源——根本没有改变它——它不会读取 NFC 标签。

当我扫描标签时 - 它什么也不做。

应该读取写为:WIFINETWORKNAME,password 的 NFC 标签

^ - 我认为 - 教程指出“将网络名称和密码(用逗号分隔)写入标签”,我已经尝试了 3 种不同的方式 - 没有任何效果。

它也不会创建新的无线配置文件 - 无论我做什么。

http://schoolofcode.wordpress.com/2013/03/20/connect-to-wifi-using-android-nfc-phone-and-nfc-tag/

它的作用:

当我扫描 NFC 标签时启动(如果我将 AAR 写入标签)

它不做什么:

  • 创建任何新的无线配置文件

  • 读取 NFC 标签和/或正确连接

我试图做的事情:

将 NFC 标签写入然后读取为:

WIFINETWORKNAME,密码

WIFI网络名称、密码

WIFI网络名称,密码

爪哇:

import java.util.List;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Connect2 extends Activity {
private EditText wifiname;
private String password;
private  NfcAdapter mAdapter;
private  PendingIntent mPendingIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connect2);

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        // Create a generic PendingIntent that will be deliver to this activity.
        // The NFC stack
        // will fill in the intent with the details of the discovered tag before
        // delivering to
        // this activity.
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // Setup an intent filter for all MIME based dispatches
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

        WifiManager wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        String connectionName = wifiInfo.getSSID();

        TextView tv=(TextView)findViewById(R.id.wifiname);
        if(connectionName==null){
            tv.setText("You are not connected  ");
        }else{

            tv.setText("You are linked to: "+connectionName+"   ");
        }

        Button close=(Button)findViewById(R.id.close);
        close.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
                System.exit(0);
            }
        });

    }
    @Override
    public void onResume(){
        super.onResume();

        if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())||NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())){
            processReadIntent(getIntent());
        }
    }
    @Override
    public void onNewIntent(Intent intent){
        setIntent(intent);
    }
    public void processReadIntent(Intent intent){
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);

        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];

        // record 0 contains the MIME type, record 1 is the AAR, if present
        Log.d("msg", msg.getRecords()[0].getPayload().toString());

        byte[]payload=msg.getRecords()[0].getPayload();
        String msgtext=null;
        try{

        //Get the Text Encoding
        String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";

        //Get the Language Code
        int languageCodeLength = payload[0] & 0077;
        String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        //Get the Text
        msgtext = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
        }catch(Exception e){

        }

        // splitting the message by comma. The first part is the name and 2nd part is the password.
        String[]tagdata=msgtext.split(",");

        String networkSSID = tagdata[0].toString();
        String networkPass = tagdata[1].toString();

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes

        conf.preSharedKey = "\""+ networkPass +"\"";
        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
        wifiManager.addNetwork(conf);

        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                 wifiManager.disconnect();
                 wifiManager.enableNetwork(i.networkId, true);
                 wifiManager.reconnect();               
                 break;
            }           
         }

        TextView wifiname=(TextView)findViewById(R.id.wifiname);
        wifiname.setTextColor( getResources().getColor(R.color.solid_red) );
        wifiname.setText("Successfully linked "+networkSSID +"   ");

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}   

尝试执行它时,我在 LogCat 中得到以下信息:

04-05 13:08:37.107: D/NfcDispatcher(905): dispatch tag: TAG: Tech [android.nfc.tech.MifareUltralight, android.nfc.tech.NfcA, android.nfc.tech.Ndef] message: NdefMessage [NdefRecord tnf=1 type=54 payload=02656E414E4452452D50435F4E4554574F524B2C2070617373776F7264]
04-05 13:08:37.107: D/NfcHandover(905): tryHandover(): NdefMessage [NdefRecord tnf=1 type=54 payload=02656E414E4452452D50435F4E4554574F524B2C2070617373776F7264]
04-05 13:08:37.117: I/ActivityManager(478): START u0 {flg=0x10008000 cmp=com.android.nfc/.NfcRootActivity (has extras)} from pid 905
04-05 13:08:37.137: I/NfcDispatcher(905): matched multiple TECH
04-05 13:08:37.147: I/ActivityManager(478): START u0 {cmp=com.android.nfc/.TechListChooserActivity (has extras)} from pid 905
04-05 13:08:37.317: D/dalvikvm(905): GC_CONCURRENT freed 7783K, 22% free 15072K/19148K, paused 9ms+9ms, total 52ms
04-05 13:08:37.327: I/ActivityManager(478): Displayed com.android.nfc/.TechListChooserActivity: +185ms (total +196ms)
04-05 13:08:38.247: D/NativeNfcTag(905): Tag lost, restarting polling loop
4

1 回答 1

0

Having made an application just like that I think that the tutorial is overly simple.

  1. It seems to use a Text Record to store the user/name and password. Not a crime punishable by death but there are better alternatives like Well-known URI Record or Handover Records, and the author seems to think it is a mime record.

  2. It says nothing about the security type, so adding the network would never work. I doubt that code has ever worked.

  3. The code totally ignores wifi-related broadcast events, which if fine, but would be necessary in 99% of real-life cases.

于 2013-04-05T22:28:18.640 回答