Android NFC广播接收机问题
我希望我的应用程序只在被激活时才收听nfc标签。为此,我尝试注册一个nfc侦听器,如下所示,但没有成功Android NFC广播接收机问题,android,broadcastreceiver,nfc,Android,Broadcastreceiver,Nfc,我希望我的应用程序只在被激活时才收听nfc标签。为此,我尝试注册一个nfc侦听器,如下所示,但没有成功 IntentFilter filter = new IntentFilter("android.nfc.action.TECH_DISCOVERED"); registerReceiver(nfcTagListener, filter); BroadcastReceiver nfcTagListener = new BroadcastReceiver() { @Over
IntentFilter filter = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
registerReceiver(nfcTagListener, filter);
BroadcastReceiver nfcTagListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.d("nfc", "" + tag.getId());
}
}
};
我还尝试在apidemos之后在我的清单中声明意图,效果很好,它启动我的活动并获取nfc标记id。但这不是我想要的,我只想在我在该活动中时检测标记id。我认为这可能与api演示中包含的以下行有关。但我不知道如何通过编程实现
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/filter_nfc">
有什么提示吗
谢谢 尝试使用前台调度系统 要启用它,您应该在活动的onCreate方法上准备一些资料:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
之后,创建IntentFilters(在我的示例中,所有操作都使用Intent过滤器处理):
之后,您需要一个字符串数组来包含支持的技术:
String[][] techList = new String[][] { new String[] { NfcA.class.getName(),
NfcB.class.getName(), NfcF.class.getName(),
NfcV.class.getName(), IsoDep.class.getName(),
MifareClassic.class.getName(),
MifareUltralight.class.getName(), Ndef.class.getName() } };
在onResume方法中,应启用前台分派方法:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techList);
并在onPause中禁用:
@Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
通过这种方式,您已经成功地初始化了所需的机制。要处理接收到的意图,应重写onNewIntent(Intent-Intent)方法
注意:如果您只想通过前台调度来处理意图,请不要在清单文件中启用意图调度系统,只需在那里为您的应用程序授予正确的权限即可
我希望这会有所帮助。如果您不想使用前台模式,您可以随时启用或禁用意图过滤器 该项目有工作样本使用前景模式,也检测
@Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
@Override
public void onNewIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
// reag TagTechnology object...
} else if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
// read NDEF message...
} else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
}
}