如何避免启动支持 NFC 的应用程序? [英] How to avoid launching an NFC-enabled app?

查看:50
本文介绍了如何避免启动支持 NFC 的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 个活动:

Assuming that I have 2 activities:

  1. MainActivity 和
  2. 第二个活动.

我想要实现的是通过发现 NFC 标签从 MainActivity 传递到 SecondActivity.我通过将意图过滤器添加到 SecondActivity 标签下的清单来使其工作.

What i want to achieve is to pass from MainActivity to SecondActivity by discovering an NFC tag. I made it work by adding the intent-filter to the manifest under the SecondActivity tag.

但我的问题是,即使应用程序被杀死,应用程序也会启动并登陆到第二个活动.基本上,我希望标签发现仅在我处于主要活动中时(点击按钮开始阅读后)发生.

But my problem is that the app will launch and land to the second activity even if the app is killed. Basically, I want the tag discovery to happen only when I'm in the main activity (after clicking a button to start reading).

我尝试在 MainActivity 的 onCreate() 方法中以编程方式添加意图过滤器并覆盖 onNewIntent() 方法,但没有成功.

I tried adding the intent-filter programatically in the onCreate() method of MainActivity and overriding the onNewIntent() method but with no luck.

我也尝试将launchMode设置为singleTop",但没有成功.

I also tried to set the launchMode to "singleTop" without success.

以下是我在MainActivity的onCreate()方法中添加的内容:

The following is what I added to the onCreate() method of the MainActivity:

adapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };

推荐答案

您可以在 MainActivity 中注册前台调度.然后,在收到 NFC Intent 后,您可以启动 SecondActivity 并将 Intent 传递给它:

You could register for the foreground dispatch in your MainActivity. Then, upon receiving the NFC intent, you can start the SecondActivity and pass the intent to it:

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

@Override
public void onPause() {
    super.onPause();
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
    adapter.disableForegroundDispatch(this);
}

@Override
public void onNewIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) ||
        NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
        NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Intent newIntent = new Intent(this, SecondActivity.class);
        newIntent.putExtra("NFC_INTENT", intent);
        startActivity(newIntent);
    }
}

这篇关于如何避免启动支持 NFC 的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆