以编程方式检查设备是否具有NFC读取器

19

有没有一种方法可以在运行时检查设备是否有NFC读卡器?我的应用程序使用NFC执行任务,但如果没有读卡器,则可以通过使用按钮执行相同的任务。

4个回答

52

希望这对你有用

NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {

    //Yes NFC available 
}else if(adapter != null && !adapter.isEnabled()){

   //NFC is not enabled.Need to enable by the user.
}else{
   //NFC is not supported
}

14
您可能需要区分 adapter == null (没有读卡器存在) 和 !adapter.isEnabled() (读卡器已关闭)。这样,用户就可以被提示启用 NFC 读卡器。 - 323go
2
嗯,'@323go',这完全取决于个人,开发者是否需要它。如果他不想显示弹出窗口,只需检查适配器!= null条件即可,我认为这并不是什么大问题。 - Sainath Patwary karnate
8
我不同意。你可以提供一个“完整”的答案,然后让开发者决定目标受众是谁。 - 323go

11
检查 Android 设备是否具有 NFC 功能的最简单方式是检查系统功能 PackageManager.FEATURE_NFC ("android.hardware.nfc"):
PackageManager pm = context.getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
    // device has NFC functionality
}

然而,现在有一些设备(至少Sony的第一款Android NFC智能手机就存在这个问题)不能正确地报告FEATURE_NFC。(那些设备不允许你通过Play Store安装需要NFC功能的应用程序,因为Play Store会检查需要NFC的应用程序。)

因此,更可靠的解决方案是由Sainath Patwary karnate描述的方法。要检查设备是否具有NFC功能(或者更确切地说,设备是否具有正在运行的NFC服务),可以使用以下代码:

NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
    // device has NFC functionality
}

如果您想检查用户设备上是否启用了NFC,可以使用NfcAdapterisEnabled()方法。但要注意,这并不总是像Sainath Patwary karnate所描述的那样简单。特别是在Android 4.0.*上,当NFC服务之前已经崩溃时,isEnabled()方法有时会抛出未记录的异常,因此您可能需要捕获这些异常。此外,在Android >= 2.3.4和<4.1(我无法在后续版本上重现此问题,但这并不意味着它不存在!)中,NFC服务停止或崩溃后第一次调用isEnabled()总是返回false,因此建议始终忽略第一次调用isEnabled()的结果。

if (nfcAdapter != null) {
    try {
        nfcAdapter.isEnabled();
    } catch (Exception e) {}
    bool isEnabled = false;
    try {
        isEnabled = nfcAdapter.isEnabled();
    } catch (Exception e) {}
    if (isEnabled) {
        // NFC functionality is available and enabled
    }
}

但是NFC服务会随意崩溃,还是只在特定情况下? - giozh
通常,在搭载NXP芯片组的设备上,当与卡片通信中断或手机无法正确识别卡片(例如,因为卡片未接收到足够的电源)时,NFC服务经常会崩溃。 - Michael Roland

2

这是我用来检测NFC存在的函数。

public static boolean deviceHasNfc() {
    // Is NFC adapter present (whether enabled or not)
    NfcManager nfcMgr = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
    if (manager != null) {
        NfcAdapter adapter = manager.getDefaultAdapter();
        return adapter != null;
    }
    return false;
}

正如 @Sainath 的回答所述,您还可以使用 adapter.isEnabled() 来检测 NFC 是否已启用。


1

对于那些使用Kotlin的人,这是一个快速的启用检查扩展,遵循上面发布的规则。

fun Context.isNfcEnabled(): Boolean {
    val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
    if (nfcAdapter != null) {
        return try {
            nfcAdapter.isEnabled
        } catch (exp: Exception) {
            // Double try this as there are times it will fail first time
            try {
                nfcAdapter.isEnabled
            } catch (exp: Exception) {
                false
            }
        }
    }
    return false
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接