NFC 已打开,但适配器未启用

NFC is on, but adapter is not enabled

我正在从事 android 项目,其中 NFC 用作通信。我面临一个奇怪的问题,当移动设备具有 NFC 时,它已启用,但它在某些设备上不起作用(调试时未启用适配器)。我正在写日志,它会打印,NFC 打开,适配器禁用。 例如:HTC One m9(os 7.0)。 OnePlus One(os 9)也会发生!但同样,它适用于其他设备。 您遇到过同样的问题吗?

这是一些代码:

object NfcUtil {

    fun getNfcAdapter(c: Context): NfcAdapter? {
        val manager = c.getSystemService(Context.NFC_SERVICE) as NfcManager
        return manager.defaultAdapter
    }

    fun doesSupportHce(c: Context): Boolean {
        return c.packageManager.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)
    }
}



val adapter = NfcUtil.getNfcAdapter(this)
if (adapter != null && NfcUtil.doesSupportHce(this)) {
     if (adapter.isEnabled) {
             tvNfcOff.extHide()
              } else {
                 tvNfcOff.extShow()
              }
     }

我认为如果 NFC 受支持并启用但 adapter 被禁用 (https://developer.android.com/reference/android/nfc/NfcAdapter#isEnabled()) 我将遵循指南并将用户重定向到设置屏幕文档中提到的意图。

如果用户回来几次,您可以监控它并显示不同的消息,而不是重定向到设置,例如:NFC 在您的设备上无法正常工作。我会检查您是否有很多用户使用这些设备,如果是,我将尝试对存在此问题的操作系统和设备进行更多研究。

稍后我将尝试使用该设备和出现此类问题的特定 Operating System 对其进行调试。我将尝试查看其他使用 NFC 的应用程序是否有相同的问题或者它们工作正常,工作正常我的意思是通信发生了,而不是其他应用程序不显示任何 warning/error 弹出消息。

如果我发现它在特定 OS 版本以及其他应用程序中存在问题,我只会尝试通知用户并获取有关问题已修复的版本的更新。否则,如果其他应用程序可以在对我不起作用的 device/OS 中成功进行 NFC 通信,我将深入挖掘。

现在我可以说你的实现没有任何问题并且看起来不错。

这可能是当前 OS 的问题,或者如果您有任何 Custom ROM 可能不完全支持或具有功能 NFC driver

另外两点可能有用的信息

1) 使用 Broadcaster 接收器在 NFC 状态改变时得到通知,因为使用快速设置下拉不会暂停你的应用程序,因此在 onResume 中重新测试 nfc 状态不起作用(用户改变不过,通过完整设置应用程序会暂停您的应用程序)

Java

中的操作示例

@Override
    protected void onCreate(Bundle savedInstanceState) {
    // All normal onCreate Stuff

    // Listen to NFC setting changes
    this.registerReceiver(mReceiver, filter);
    }

// Listen for NFC being turned on while in the App
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
                final int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
                        NfcAdapter.STATE_OFF);
                switch (state) {
                    case NfcAdapter.STATE_OFF:
                    // Tell the user to turn NFC on if App requires it
                        break;
                    case NfcAdapter.STATE_TURNING_OFF:
                        break;
                    case NfcAdapter.STATE_ON:
                        // Do something with this to enable NFC listening
                        break;
                    case NfcAdapter.STATE_TURNING_ON:
                        break;
                }
            }
        }
    };

2) 不要假设设备有 NFC 设置页面,如果您的应用程序可以使用和不使用 NFC,如果适配器是 null 不要假设您可以启动 NFC Intent @denis_lor 建议的设置页面,因为如果 OS 没有要打开的 NFC 适配器,这将导致崩溃。