Android 实现 NFC 读取门禁卡

引言

在现代社会中,门禁卡已经成为了人们生活中不可或缺的一部分。为了方便用户,将门禁卡集成到手机中已经成为了一种趋势。本文将指导你如何使用 Android 开发技术实现 NFC 读取门禁卡的功能。

流程图

flowchart TD
  A[初始化 NFC Adapter] --> B[创建 Intent Filter]
  B --> C[设置技术类型]
  C --> D[创建 PendingIntent]
  D --> E[注册 NFC 监听器]
  E --> F[处理 NFC 数据]

整体流程

  1. 初始化 NFC Adapter
  2. 创建 Intent Filter
  3. 设置技术类型
  4. 创建 PendingIntent
  5. 注册 NFC 监听器
  6. 处理 NFC 数据

详细步骤和代码示例

1. 初始化 NFC Adapter

首先,我们需要在 onCreate 方法中初始化 NFC Adapter。这将确保我们可以与 NFC 通信。

private NfcAdapter mNfcAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter == null) {
        // NFC 适配器不可用
        return;
    }
}

2. 创建 Intent Filter

Intent Filter 用于指定我们感兴趣的 NFC Intent。在这个案例中,我们将指定 ACTION_TECH_DISCOVERED,以便在检测到 NFC 标签时收到通知。

IntentFilter[] intentFiltersArray = new IntentFilter[] { 
    new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
};

3. 设置技术类型

我们需要指定我们感兴趣的 NFC 技术类型。在这个案例中,我们将选择 MifareClassic。

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

4. 创建 PendingIntent

我们需要创建一个 PendingIntent,以便我们的应用程序可以在 NFC 事件发生时接收到通知。

PendingIntent pendingIntent = PendingIntent.getActivity(
    this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0
);

5. 注册 NFC 监听器

onResume 方法中,我们需要注册我们的 NFC 监听器,以确保我们可以接收到 NFC 事件。

@Override
protected void onResume() {
    super.onResume();

    // 检查 NFC 适配器是否启用
    if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
        // 提示用户启用 NFC
        startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
    }

    // 注册 NFC 监听器
    mNfcAdapter.enableForegroundDispatch(
        this, pendingIntent, intentFiltersArray, techListsArray
    );
}

6. 处理 NFC 数据

onNewIntent 方法中,我们可以处理接收到的 NFC 数据。在这个案例中,我们将简单地打印出收到的数据。

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag != null) {
            MifareClassic mifareClassic = MifareClassic.get(tag);
            // 处理 MifareClassic 数据
            // ...
        }
    }
}

以上就是实现 Android NFC 读取门禁卡的基本步骤和代码示例。通过按照上述步骤进行开发,你将能够成功读取门禁卡上的数据。希望对你有所帮助!

参考资料:

  • [Android 官方文档](
  • [MifareClassic 官方文档](