我希望我的应用程序仅在激活时监听 nfc 标签。为此,我尝试按如下方式注册一个 nfc 监听器,但没有成功。
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 在 list 中声明 Intent ,并且工作完美,它启动了我的 Activity 并获取 nfc 标签 ID。但这不是我想要的,我只想当我在该 Activity 中时检测标签 ID。我认为这可能与 api 演示中包含的以下行有关。但我不知道如何以编程方式做到这一点
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/filter_nfc">
有什么提示吗?
谢谢!
最佳答案
尝试使用前台调度系统。
要启用它,在 Activity 的 onCreate 方法上,您应该准备一些东西:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
之后,创建 IntentFilters(在我的示例中,所有操作都使用 Intent Filters 处理):
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
try {
tech.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
IntentFilter[] intentFiltersArray = new IntentFilter[] { tag, ndef, tech };
之后,您将需要一个字符串数组来包含支持的技术:
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);
}
至此,您已经成功初始化了所需的机制。要处理接收到的 Intent,您应该重写 onNewIntent(Intent Intent) 方法。
@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)) {
}
}
注意:如果您只想通过前台调度来处理 Intent ,请不要在 list 文件中启用 Intent 调度系统,只需为您的应用程序授予正确的权限即可。
希望对您有所帮助。
关于android - NFC 广播接收器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5685946/