首页 > 解决方案 > NfcAdapter.getDefaultAdapter 返回 null

问题描述

我有 3 个不同devicesNFC. 其中 2 个NfcAdapter.getDefaultAdapter(this)返回应有的内容,但在第三个设备上返回null。在第三台设备上安装了应用程序(不是我的),可以正常使用NFC cards. 第三个设备是SUNMI P1N-G。有任何想法吗?

主要活动:

package com.test.nfctest;

import androidx.appcompat.app.AppCompatActivity;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private NfcAdapter nfcAdapter;
    TextView text1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text1 = (TextView) findViewById(R.id.text1);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter==null) {
            text1.setText("no nfc");
        } else {
            text1.setText("NFC");
        }

    }
}

安卓清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.nfctest">
    <uses-permission android:name="android.permission.NFC"/>
    <uses-feature android:name="android.hardware.nfc" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

标签: javaandroidnfc

解决方案


获得空适配器有几个原因。 http://androidxref.com/6.0.1_r10/xref/frameworks/base/core/java/android/nfc/NfcAdapter.java#494

根据 NfcManager 中的评论,有两种方式获取 NFC 适配器:

  1. 使用 {@link android.content.Context#getSystemService(java.lang.String)} 和 {@link Context#NFC_SERVICE} 创建一个 {@link NfcManager},然后调用 {@link #getDefaultAdapter} 来获取 {@link Nfc适配器}。
    NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE); NfcAdapter adapter = manager.getDefaultAdapter();
  2. 您可以调用静态帮助程序 {@link NfcAdapter#getDefaultAdapter(android.content.Context)}。

您可以尝试上述替代方法#1。


推荐阅读