【问题标题】:Android NFC in Embarcadero XE5Embarcadero XE5 中的 Android NFC
【发布时间】:2014-03-26 17:50:22
【问题描述】:

尝试让 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 调用它

但由于我以前从未这样做过,我不知道如何进行

【问题讨论】:

    标签: android delphi nfc delphi-xe5


    【解决方案1】:

    编辑似乎我错过了一个标签,并且 OP 不要求 Java 代码。无论如何都要留下这个以供将来参考

    您的猜测是正确的,尽管可以在 AndroidManifest.xml 中定义您想要监听的意图,但前台调度确实将您的应用置于 前端,让您能够捕获所有已启动的 NFC 意图。

    docs 中描述的方式给了你一个线索。

    我假设您熟悉 Android 活动、Intent Dispatching 等的lifecycle


    结构

    使用以下结构,您将拥有 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 尝试处理意图的顺序如下:

    1. ACTION_NDEF_DISCOVERED
    2. ACTION_TECH_DISCOVERED
    3. ACTION_TAG_DISCOVERED

    所以我们确保我们的应用是第一个被 Android 查看的。


    启用 FGD

    将下面这行代码放入onResume方法中:

    if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, pendingIntent, mIntentFilters, mTechLists);
        }
    

    为什么会出现在onResume 中?正如文档所述:enableForegroundDispatch() must be called from the main thread and only when the activity is in the foreground (calling in onResume() guarantees this)

    这应该使您的应用能够在实际运行时接收意图。 如果您想在不运行时接收 Intent,则必须转到 AndroidManifest。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2016-02-03
      相关资源
      最近更新 更多