【问题标题】:Android Intent reopening activityAndroid Intent 重新打开活动
【发布时间】:2017-01-08 22:40:04
【问题描述】:

我有一个问题,我没有在这个网站上找到解决方案,但如果这是一个重复的问题,我很抱歉。

我正在开发一个应用程序,该应用程序可用作在员工开始/结束工作时进行注册的终端,等等。它的工作方式是在 NFC 开启的情况下,他们扫描他们的 NFC 卡,我的应用程序读取它们并最终将适当的信息发送到服务器。

但是,如果应用程序已经打开(它应该一直打开,所以这是一个问题)并且扫描了 NFC 卡,它会重新打开应用程序。当然,这样做是因为我在清单中已经这样设置了。但是,如果我不在清单中添加所有这些行,我将找不到让我的应用接收 NFC 扫描意图的方法:

<intent-filter>
            <action android:name="android.nfc.action.TAG_DISCOVERED" />

            <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

我试过只写不带,但在这种情况下,它不会读取卡,而是会在手机上显示程序选择器,或者如果手机没有合适的应用程序,它只会显示"NFC read error"

有人对此有解决方案吗?这是我项目的最后一步,我遇到了很多麻烦,希望能得到任何帮助。这可能是我没有看到的一些简单的东西,但无论哪种方式我都会很感激。

【问题讨论】:

  • 您是否尝试过在清单中的活动下设置 android:launchMode="singleInstance"
  • 是的,我做了,但我没有添加被覆盖的 OnNewIntent 方法,这解决了我想要的问题。
  • intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED) 成功为我检查了它。 @RaviGadipudi
  • 太棒了。快乐编码...

标签: android android-studio android-intent intentfilter


【解决方案1】:

Android Activity 有不同的启动模式。如果您设置单个实例,它将使用已打开的活动并且不会创建新活动。您可以在覆盖方法onNewIntent()中阅读新意图

protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  // read intent values here
}

For various activity elements

【讨论】:

  • 这正是我所需要的,谢谢!如果您不介意告诉我,我如何确定意图是 NFC 的?而不是例如我从另一个打开此活动的那个?
  • 寻找intent.getAction(),它应该匹配你的“android.nfc.action.TAG_DISCOVERED”。如果此解决方案不起作用,请告诉我。我会通过深入研究来帮助你。
  • 不错的答案和参考
【解决方案2】:

您可以使用广播接收器, - 首先启动接收器到您的活动

IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("whateveryouwant");

    notificationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
// here you can read the intent and customize the action;
            int usage = intent.getIntExtra("usage",1000); 


            }


        }
    };
  • 第二次注册广播

    registerReceiver(notificationBroadcastReceiver,intentFilter);

  • 最后在 onDestroy 方法中取消注册到广播

    @覆盖 受保护的无效 onDestroy() {

    if(notificationBroadcastReceiver != null){
    
        unregisterReceiver(notificationBroadcastReceiver);
        notificationBroadcastReceiver = null;
    }
    super.onDestroy();
    

    }

在这样做之后,您可以发送广播()而不是意图活动

小指南:https://developer.android.com/reference/android/content/BroadcastReceiver.html

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多