Android应用仅为一个活动启用NFC

是否可以为 Android中的一项活动启用NFC以支持NFC应用程序?

我读过这个,
Reading NFC tags only from a particuar activity

但是设备仍在扫描应用程序的所有活动上的标签.

编辑:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfccheckout" >

    <uses-feature
        android:name="android.hardware.nfc"
        android:required="true" />

    <uses-permission android:name="android.permission.NFC" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activities.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.ReceiveActivity"
            android:label="@string/title_activity_receive" >
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="application/json+com.example.nfccheckout" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.CreatePayloadActivity"
            android:label="@string/title_activity_create_payload" >
        </activity>
        <activity
            android:name=".activities.ConfirmationActivity"
            android:label="@string/title_activity_confirmation" >
        </activity>
    </application>

</manifest>

解决方法

如果您想要在某个活动位于前台时对NFC发现事件(NDEF_DISCOVERED,TECH_DISCOVERED,TAG_DISCOVERED)进行处理,则可以为 foreground dispatch system注册该活动.然后,该活动可以忽略这些事件(它将在其onNewIntent中接收() 方法.

这样可以防止将NFC发现事件传递给在清单中注册了NFC disovery intent过滤器的任何其他活动(因此应用程序和任何其他已安装的应用程序中的活动).

但是,此方法不会禁用设备的NFC调制解调器.因此,NFC芯片仍会轮询标签,但不会向任何应用报告.

因此,您要禁用NFC的所有活动都会执行以下操作:

public void onResume() {
    super.onResume();
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
    nfcAdapter.enableForegroundDispatch(this,pendingIntent,null,null);
}

public void onPause() {
    super.onPause();
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.disableForegroundDispatch(this);
}

public void onNewIntent(Intent intent) {
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        // drop NFC events
    }
}

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...