试图让 NFC 在 Embarcadero XE5 中的 Android 上运行。 从以下内容开始:https://forums.embarcadero.com/thread.jspa?threadID=97574 这似乎正在工作。现在想为 NFC Intent 注册回调
Java 方法:
1. Register current activity as a listener
...
2. Receive Intent
@Override
protected void onNewIntent(Intent intent) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] msgs = NfcUtils.getNdefMessages(intent);
}
}
来源:http://www.jessechen.net/blog/how-to-nfc-on-the-android-platform/
Delphi 方法(如我所想):
1. Define methods available in Java interface
来源:https://forums.embarcadero.com/thread.jspa?messageID=634212
Question:
How do I register a listener for NFC intent messages and
how do I eventually get messages?
我的猜测是调用 enableForegroundDispatch
方法。定义如下:
procedure enableForegroundDispatch; cddcl;
从 Android API 调用它
但由于我以前从未这样做过,我不知道如何进行
最佳答案
编辑:似乎我错过了一个标签,并且 OP 不要求 Java 代码。无论如何都要留下这个以供将来引用
您的猜测是正确的,尽管可以在 AndroidManifest.xml 中定义您想要监听的 Intent ,但前台调度确实将您的应用置于 前端,让您能够捕获所有已启动的 NFC Intent 。
docs 中描述的方式给你一个线索。
我假设您熟悉 lifecycle Android Activity 、Intent Dispatching 等。
结构
使用以下结构,您将拥有 4 个字段:
private PendingIntent pendingIntent;
private IntentFilter[] mIntentFilters;
private String[][] mTechLists;
private NfcAdapter mNfcAdapter;
在 onCreate
你会得到:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
mIntentFilters = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)};
mTechLists = new String[][]{new String[]{Ndef.class.getName()},
new String[]{NdefFormatable.class.getName()}};
}
这并没有实际上还没有启用前台调度,它只是准备工作。 应用程序将收到 Ndef 和 NdefFormatable technologies 我们为什么要订阅 ACTION_NDEF_DISCOVERED ?
Android 尝试处理 Intent 的顺序如下:
- ACTION_NDEF_DISCOVERED
- ACTION_TECH_DISCOVERED
- ACTION_TAG_DISCOVERED
所以我们确保我们的应用是第一个被 Android 查看的。
启用 FGD
在onResume
方法中加入如下代码:
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, mIntentFilters, mTechLists);
}
为什么会出现在 onResume
中?正如文档所述: enableForegroundDispatch() 必须从主线程调用,并且仅当 Activity 处于前台时(调用 onResume() 保证这一点)
这应该使您的应用能够在实际运行时接收 Intent 。 如果您想在不运行时接收 Intent,则必须转到 AndroidManifest。
关于Embarcadero XE5 中的 Android NFC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21998395/