检查附近是否有 nfc 标签

Check if nfc tag is near by

我想让我的 phone 检测附近(靠近它的表面)是否有 nfc 标签 以下代码没有错误,但一旦我 运行 应用程序,它就会崩溃。如果你们中有人可以查看我的代码并检查是否有我看不到的东西,那将非常有帮助。下面是 运行timeerror。

public class AccessControlActivity extends AppCompatActivity {

    NfcAdapter nfcAdapter;

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

         nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        // Checks if there is NFC function
        if(nfcAdapter != null && nfcAdapter.isEnabled()) {
            //Toast.makeText(this, "NFC works", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(this, "NFC is not available!", Toast.LENGTH_SHORT).show();
            //finish();
        }


    }


    @Override
    protected  void onNewIntent(Intent intent) {
        Toast.makeText(this, "NFC intent received", Toast.LENGTH_LONG).show();
        super.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        Intent intent = new Intent(this, AccessControlActivity.class);
        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        IntentFilter[] intentFilters = new IntentFilter[]{};

        nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);


        super.onResume();
    }

    @Override
    protected void onPause() {
        nfcAdapter.disableForegroundDispatch(this);


        super.onPause();
    }
}

运行timeerror 看起来像这样:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.nfc.netvision, PID: 5484
    java.lang.RuntimeException: Unable to resume activity {com.nfc.netvision/com.nfc.netvision.AccessControlActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4341)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4373)
        at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7464)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.NfcAdapter.enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][])' on a null object reference
        at com.nfc.netvision.AccessControlActivity.onResume(AccessControlActivity.java:116)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1456)
        at android.app.Activity.performResume(Activity.java:8125)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4331)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4373) 
        at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52) 
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2043) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:216) 
        at android.app.ActivityThread.main(ActivityThread.java:7464) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:955) 
I/Process: Sending signal. PID: 5484 SIG: 9

因此,您检查 onCreate 中的 nfcAdapter != null 并只是祝酒词,然后您的应用程序将盲目地尝试使用 [=14= 中可能的 null 适配器].

这可以解释 onResume 中的 Attempt to invoke virtual method on a null object reference 因为变量 nfcAdapter 可能是 onResume[=23= 中的 null ]

您应该在 onResume

中再次检查 null

此外,您的 Intent 过滤器看起来也不正确,它们的代码要么导致没有 Intent 发送给您,要么导致所有包括非 NFC Intent 的相反发送给您。

当出现任何类型的标签时调用更正常的代码。

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

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndefDetected.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {}
        IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if(nfcAdapter!= null)
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(nfcAdapter!= null)
            nfcAdapter.disableForegroundDispatch(this);
    }