【问题标题】:How to check whether NFC is enabled or not in android?如何检查android中是否启用了NFC?
【发布时间】:2011-10-01 06:42:09
【问题描述】:

如何以编程方式检查 NFC 是否已启用?有什么方法可以通过我的程序在设备上启用 NFC?请帮帮我

【问题讨论】:

    标签: android nfc


    【解决方案1】:

    这可以简单地使用以下代码来完成:

    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    
    if (nfcAdapter == null) {
        // NFC is not available for device
    } else if (!nfcAdapter.isEnabled()) {
        // NFC is available for device but not enabled
    } else {
        // NFC is enabled
    }
    

    请记住,即使在使用您的应用时,用户也可以关闭 NFC。

    来源:https://developer.android.com/guide/topics/connectivity/nfc/nfc#manifest

    虽然您无法自行以编程方式启用 NFC,但您可以要求用户通过按钮打开 NFC 设置来启用它,如下所示:

    Intent intent
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        intent = new Intent(Settings.ACTION_NFC_SETTINGS);
    } else {
        Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
    }
    
    startActivity(intent);
    

    【讨论】:

    • 这是一个更完整的答案,包括如何将用户引导至 NFC 设置。谢谢。
    【解决方案2】:
    NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
    NfcAdapter adapter = manager.getDefaultAdapter();
    if (adapter != null && adapter.isEnabled()) {
        // adapter exists and is enabled.
    }
    

    您无法以编程方式启用 NFC。用户必须通过设置或硬件按钮手动完成。

    【讨论】:

    • 所以如果返回值为FALSE,说明设备没有NFC功能,是不是@userSeven7s?
    • 这是不正确的。如果适配器为空,则设备没有 NFC。关于Developer website的解释
    【解决方案3】:
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getApplicationContext());
        try {
            if (mNfcAdapter != null) {
                result = true;
            }
        }
    

    我们可以使用带有上下文的 NfcAdapter 进行验证。

    【讨论】:

      【解决方案4】:

      使用PackageManagerhasSystemFeature("android.hardware.nfc"),匹配您应该在清单中包含的<uses-feature android:name="android.hardware.nfc" android:required="false" /> 元素。

      从 2.3.3 开始,您还可以使用 NfcAdapter.getDefaultAdapter() 获取适配器(如果可用)并调用其 isEnabled() 方法来检查当前是否打开了 NFC。

      【讨论】:

        【解决方案5】:

        我在这里可能有点晚了,但我已经实现了一个“完整的”example 并检测到

        1. NFC 功能(硬件),以及
        2. 初始 NFC 状态(在设置中启用或禁用),以及
        3. 状态变化

        我还添加了一个相应的 Beam example ,它使用了

        nfcAdapter.isNdefPushEnabled()
        

        后来的 Android 版本中引入了检测光束状态的方法,如 2) 和 3)。

        【讨论】:

        • 您能否更新您的答案,因为 Google 代码已关闭。
        • Android Beam 不再受支持。
        猜你喜欢
        • 2014-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-09
        • 2017-12-24
        • 1970-01-01
        相关资源
        最近更新 更多