使用NFC读取RFID标签

时间:2014-07-10 17:27:42

标签: android nfc rfid mifare

我想开发一个Android应用程序女巫可以读取RFID卡的ID(mifare经典类型A)使用NFC但我的应用程序检测到卡但它没有返回任何东西..帮助请btw我hqve 2 class < / p>

类MainActivity:

package com.example.nfcreader;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
static String TAG = "NFCREADER";

NFCForegroundUtil nfcForegroundUtil = null;

private TextView  info;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   info = (TextView)findViewById(R.id.title);

    nfcForegroundUtil = new NFCForegroundUtil(this);
}

public void onPause() {
    super.onPause();
    nfcForegroundUtil.disableForeground();
}   

public void onResume() {
    super.onResume();
    nfcForegroundUtil.enableForeground();

    if (!nfcForegroundUtil.getNfc().isEnabled())
    {
        Toast.makeText(getApplicationContext(), 
                "Please activate NFC and press Back to return to the application!", 
                Toast.LENGTH_LONG).show();
        startActivity(
                new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
    }

}

public void onNewIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    /*StringBuilder sb = new StringBuilder();
    for(int i = 0; i < tag.getId().length; i++){
        sb.append(new Integer(tag.getId()[i]) + " ");
    }*/
   info.setText("TagID: " + bytesToHex(tag.getId()));    
    //byte[] id = tag.getId();
}

/**
 *  Convenience method to convert a byte array to a hex string.
 *
 * @param  data  the byte[] to convert
 * @return String the converted byte[]
 */

public static String bytesToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
        buf.append(byteToHex(data[i]).toUpperCase());
        buf.append(" ");
    }
    return (buf.toString());
}

/**
 *  method to convert a byte to a hex string.
 *
 * @param  data  the byte to convert
 * @return String the converted byte
 */
public static String byteToHex(byte data) {
    StringBuffer buf = new StringBuffer();
    buf.append(toHexChar((data >>> 4) & 0x0F));
    buf.append(toHexChar(data & 0x0F));
    return buf.toString();
}

/**
 *  Convenience method to convert an int to a hex char.
 *
 * @param  i  the int to convert
 * @return char the converted char
 */
public static char toHexChar(int i) {
    if ((0 <= i) && (i <= 9)) {
        return (char) ('0' + i);
    } else {
        return (char) ('a' + (i - 10));
    }
  }    

}

类NFCForegroundUtil:

package com.example.nfcreader;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcA;
import android.util.Log;

public class NFCForegroundUtil {
 private NfcAdapter nfc;

private Activity activity;
private IntentFilter intentFiltersArray[];
private PendingIntent intent;
private String techListsArray[][];

public NFCForegroundUtil(Activity activity) {
    super();
    this.activity = activity; 
    nfc = NfcAdapter.getDefaultAdapter(activity.getApplicationContext());

    intent = PendingIntent.getActivity(activity, 0, new Intent(activity,
            activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

    try {
        ndef.addDataType("*/*");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("Unable to speciy */* Mime Type", e);
    }
    intentFiltersArray = new IntentFilter[] { ndef };

    techListsArray = new String[][] { new String[] { NfcA.class.getName() } };

}

public void enableForeground()
{
    Log.d("demo", "Foreground NFC dispatch enabled");
    nfc.enableForegroundDispatch(
            activity, intent, intentFiltersArray, techListsArray);     
}

public void disableForeground()
{
    Log.d("demo", "Foreground NFC dispatch disabled");
    nfc.disableForegroundDispatch(activity);
}

public NfcAdapter getNfc() {
    return nfc;
  }   
}

和我的AndroidManifest

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nfcreader"
android:versionCode="1"
android:versionName="1.0" >

 <uses-sdk 
   android:minSdkVersion="10"
   android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />

   <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

<intent-filter>

 <action android:name="android.nfc.action.TAG_DISCOVERED"/>
 <category android:name="android.intent.category.DEFAULT"/> 
</intent-filter> 

    </activity>
</application>

</manifest>

4 个答案:

答案 0 :(得分:2)

我会假设你看过这里:

Near field communication overview

在这里:

NFC basics

我注意到onNewIntent在其他情境中有些奇怪的行为,所以我会这样做,因为上面的第二个链接表明:

public void onResume() {
    super.onResume();
    ...
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        }
    }
    //process the msgs array
}

还要确保根据第二个链接指南

正确设置了清单

答案 1 :(得分:1)

您当前用于前台调度系统的intent过滤器对包含MIME类型*/*的NDEF记录的标记很敏感。请注意,这似乎匹配某些设备上的任何MIME类型,即使文档明确指出(请参阅this)通配符匹配只能在子类型中使用(例如{{ 1}})。因此,这可能只匹配包含text/*类型的MIME类型。

无论如何,因为你想触发任何A类标签,我建议你改变你的意图过滤器以实际触发任何类型A标签:

*/something

此外,您应避免在应用的清单中使用PendingIntent intent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter[] intentFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED), }; String[][] techLists = new String[][] { new String[] { NfcA.class.getName() }, }; nfc.enableForegroundDispatch( activity, intent, intentFilters, techLists); 意图过滤器。此意图过滤器仅用作后备(以及对API级别9的向后兼容性)。如果您希望应用由代码启动,请使用特定的过滤器(即TAG_DISCOVERED的{​​{1}}过滤器或标签上的NDEF消息的TECH_DISCOVERED过滤器。 / p>

答案 2 :(得分:1)

所有支持NFC的智能设备均不支持Mifare。基本上,NFC控制器需要由恩智浦控制器制造。例如。 nexus 5使用broadcom芯片组,因此无法读取mifare。这是b / c NXP拥有mifare classic,因此拥有适当的crypto-1算法。 Mifare classic位于iso14443第3和第4部分之间。

答案 3 :(得分:0)

我只需要在Android 9上使用Samsung Tab Active Pro和没有Ndef数据的MifareClassic NfcA做类似的事情。

我在这里找到了一个可行的示例应用程序:

https://github.com/xamarin/monodroid-samples/tree/master/CardReader

行得通。关键部分之一如下:

// Recommend NfcAdapter flags for reading from other Android devices. Indicates that this
// activity is interested in NFC-A devices (including other Android devices), and that the
// system should not check for the presence of NDEF-formatted data (e.g. Android Beam).
public NfcReaderFlags READER_FLAGS = NfcReaderFlags.NfcA | NfcReaderFlags.SkipNdefCheck;

正在传递到这里:

    private void EnableReaderMode ()
    {
        Log.Info (TAG, "Enabling reader mode");
        Activity activity = this.Activity;
        NfcAdapter nfc = NfcAdapter.GetDefaultAdapter (activity);
        if (nfc != null)
        {
            nfc.EnableReaderMode(activity, mLoyaltyCardReader, READER_FLAGS , null);
        }
    }