首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Android中同时读取多个NFC标签

,可以通过以下步骤实现:

  1. 确保设备支持NFC功能,并且已经开启了NFC功能。
  2. 在AndroidManifest.xml文件中添加NFC权限:<uses-permission android:name="android.permission.NFC" />
  3. 创建一个NFC适配器,并注册一个NFC标签侦听器。
代码语言:java
复制
// 获取NFC适配器
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);

// 创建一个PendingIntent,用于处理NFC标签的意图
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

// 创建一个Intent过滤器,用于过滤NDEF数据
IntentFilter ndefIntentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
    ndefIntentFilter.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
    e.printStackTrace();
}

// 创建一个Intent过滤器数组
IntentFilter[] intentFiltersArray = new IntentFilter[]{ndefIntentFilter};

// 创建一个技术列表数组
String[][] techListsArray = new String[][]{{NfcF.class.getName()}, {NfcA.class.getName()}};

// 注册NFC标签侦听器
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
  1. 在Activity的onNewIntent方法中处理NFC标签的读取。
代码语言:java
复制
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    
    // 获取标签的ID
    byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
    String tagIdString = ByteArrayToHexString(tagId);
    
    // 获取标签的数据
    Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    if (rawMessages != null) {
        NdefMessage[] messages = new NdefMessage[rawMessages.length];
        for (int i = 0; i < rawMessages.length; i++) {
            messages[i] = (NdefMessage) rawMessages[i];
        }
        
        // 处理标签的数据
        for (NdefMessage message : messages) {
            NdefRecord[] records = message.getRecords();
            for (NdefRecord record : records) {
                byte[] payload = record.getPayload();
                String payloadString = new String(payload, StandardCharsets.UTF_8);
                
                // 处理标签的数据
                // ...
            }
        }
    }
}

// 将字节数组转换为十六进制字符串
private String ByteArrayToHexString(byte[] byteArray) {
    StringBuilder sb = new StringBuilder(byteArray.length * 2);
    for (byte b : byteArray) {
        int v = b & 0xff;
        if (v < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(v));
    }
    return sb.toString();
}

以上代码片段演示了如何在Android中同时读取多个NFC标签。在实际应用中,可以根据具体需求进行进一步的处理和解析标签数据。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券