Android实现NFC读写

一、NFC是什么?

近距离无线通讯技术,这个技术由非接触式射频识别(RFID)演变而来,由飞利浦半导体(现恩智浦半导体公司)、诺基亚和索尼共同研制开发,其基础是RFID及互连技术。近场通信(Near Field Communication,NFC)是一种短距高频的无线电技术,在13.56MHz频率运行于20厘米距离内。其传输速度有106 Kbit/秒、212 Kbit/秒或者424 Kbit/秒三种。目前近场通信已通过成为ISO/IEC IS 18092国际标准、ECMA-340标准与ETSI TS 102 190标准。NFC采用主动和被动两种读取模式。

NFC通信模式主要有以下几种(信息来源):

1.读卡器模式(Reader/writer mode):

作为非接触读卡器使用,比如从海报或者展览信息电子标签上读取相关信息。亦可实现NFC手机之间的数据交换,对于企业环境的中的文件共享,或者对于多玩家的游戏应用,都将带来诸多的便利。

2. 点对点模式(P2Pmode):

此模式和红外线差不多,可用于数据交换,只是传输距离较短,传输创建速度较快,传输速度也快些,功耗低(蓝牙也类似)。将两个具备NFC功能的设备无线链接,能实现数据点对点传输,如下载音乐、交换图片或者同步设备地址薄。因此通过NFC,多个设备如数位相机、PDA、计算机和手机之间都可以交换资料或者服务。

3.卡模式(Cardemulation):

这个模式其实就是相当于一张采用RFID技术的IC卡,可以替代大量的IC卡(包括信用卡)使用的场合,如商场刷卡、公交卡、门禁管制,车票,门票等等。此种方式下,有一个极大的优点,那就是卡片通过非接触读卡器的 RF 域来供电,即使寄主设备(如手机)没电也可以工作。

二、如何使用与集成到项目?

1、首先在manifests里面声明NFC和添加相应的权限;

<uses-feature  
        android:name="android.hardware.nfc"  
        android:required="true" />  
<uses-permission android:name="android.permission.NFC" />

2、在Activity标签中声明识别NFC标签;

<activity android:name=".Activity.Main.NFCActivity">  
    <intent-filter>  
        <action android:name="android.nfc.action.TAG_DISCOVERED" />  

        <category android:name="android.intent.category.DEFAULT" />  

        <data android:mimeType="*/*" />  
    </intent-filter>  
</activity>

3、封装NFC的读写,方便调用;

public class NfcUtils {  

    //nfc  
    public static NfcAdapter mNfcAdapter;  
    public static IntentFilter[] mIntentFilter = null;  
    public static PendingIntent mPendingIntent = null;  
    public static String[][] mTechList = null;  

    /** 
     * 构造函数,用于初始化nfc
     */  
    public NfcUtils(Activity activity) {  
        mNfcAdapter = NfcCheck(activity);  
        NfcInit(activity);  
    }  

    /** 
     * 检查NFC是否打开 
     */  
    public static NfcAdapter NfcCheck(Activity activity) {  
        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);  
        if (mNfcAdapter == null) {  
            return null;  
        } else {  
            if (!mNfcAdapter.isEnabled()) {  
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);  
                activity.startActivity(setNfc);  
            }  
        }  
        return mNfcAdapter;  
    }  

    /** 
     * 初始化nfc设置 
     */  
    public static void NfcInit(Activity activity) {  
        mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);  
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);  
        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);  
        try {  
            filter.addDataType("*/*");  
        } catch (IntentFilter.MalformedMimeTypeException e) {  
            e.printStackTrace();  
        }  
        mIntentFilter = new IntentFilter[]{filter, filter2};  
        mTechList = null;  
    }  

    /**  
     * 读取NFC的数据  
     */  
    public static String readNFCFromTag(Intent intent) throws UnsupportedEncodingException {  
        Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);  
        if (rawArray != null) {  
            NdefMessage mNdefMsg = (NdefMessage) rawArray[0];  
            NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];  
            if (mNdefRecord != null) {  
                String readResult = new String(mNdefRecord.getPayload(), "UTF-8");  
                return readResult;  
            }  
        }  
        return "";  
    }  


    /** 
     * 往nfc写入数据 
     */  
    public static void writeNFCToTag(String data, Intent intent) throws IOException, FormatException {  
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
        Ndef ndef = Ndef.get(tag);  
        ndef.connect();  
        NdefRecord ndefRecord = NdefRecord.createTextRecord(null, data);  
        NdefRecord[] records = {ndefRecord};  
        NdefMessage ndefMessage = new NdefMessage(records);  
        ndef.writeNdefMessage(ndefMessage);  
    }  

    /** 
     * 读取nfcID 
     */  
    public static String readNFCId(Intent intent) throws UnsupportedEncodingException {  
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
        String id = ByteArrayToHexString(tag.getId());  
        return id;  
    }  

    /** 
     * 将字节数组转换为字符串 
     */  
    private static String ByteArrayToHexString(byte[] inarray) {  
        int i, j, in;  
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};  
        String out = "";  

        for (j = 0; j < inarray.length; ++j) {  
            in = (int) inarray[j] & 0xff;  
            i = (in >> 4) & 0x0f;  
            out += hex[i];  
            i = in & 0x0f;  
            out += hex[i];  
        }  
        return out;  
    }  
}  

4、在NFCActivity代码中的使用、使用标签的前台调度系统;

@Override  
public void initData() {  
    //nfc初始化设置  
    NfcUtils nfcUtils = new NfcUtils(this);  
} 

@Override  
protected void onResume() {  
    super.onResume();  
    //开启前台调度系统  
    NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);  
}
@Override  
protected void onPause() {  
    super.onPause();  
    //关闭前台调度系统  
    NfcUtils.mNfcAdapter.disableForegroundDispatch(this);  
}

@Override  
protected void onNewIntent(Intent intent) {  
    super.onNewIntent(intent);  
    //当该Activity接收到NFC标签时,运行该方法  
    //调用工具方法,读取NFC数据  
    String str = NfcUtils.rendFromTag(intent);  
} 

5、判断手机是否支持NFC

PackageManager packageManager = this.getPackageManager();
boolean b1 = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
Toast.makeText(context, "是否支持nfc:" + b1, 1).show();

  • 7
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Android Studio中实现NFC读写功能,需要以下几个步骤: 1. 确保你的设备支持NFC功能,并在AndroidManifest.xml文件中添加必要的权限和配置。例如,添加以下权限到<manifest>标签中: ```xml <uses-permission android:name="android.permission.NFC" /> ``` 并在<application>标签内添加以下配置: ```xml <uses-feature android:name="android.hardware.nfc" android:required="true" /> <intent-filter> <action android:name="android.nfc.action.TECH_DISCOVERED" /> </intent-filter> ``` 2. 创建一个NFC Adapter实例,并启用前台调度模式以处理NFC意图。这可以在Activity或Service中完成。例如,在你的Activity的onCreate()方法中添加以下代码: ```java NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); if (nfcAdapter != null && nfcAdapter.isEnabled()) { PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter[] intentFiltersArray = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)}; String[][] techListsArray = new String[][]{{android.nfc.tech.NfcA.class.getName()}}; nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray); } ``` 3. 处理NFC意图,读取或写入NFC标签的数据。在你的Activity中,重写onNewIntent()方法并添加以下代码: ```java @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // 在这里执行读取或写入NFC标签的操作 } } ``` 你可以使用Tag对象来读取或写入NFC标签的数据。你可以使用技术类(例如Ndef或MifareClassic)来解析标签上的数据,并执行相应的操作。 这些是实现Android Studio中NFC读写功能的基本步骤。请根据你的需求和具体情况进行适当的调整和扩展。参考中的示例代码可以帮助你更详细地了解NFC读写功能的实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值