Android 打算重新开放 activity

Android Intent reopening activity

我有一个问题,我尚未在此站点上找到解决方案,但如果这是一个重复的问题,我深表歉意。

我正在开发一个应用程序,作为员工 start/finish 工作时的注册终端,还有许多其他事情。它的工作方式是,在 NFC 打开的情况下,他们扫描他们的 NFC 卡,我的应用程序读取它们并最终将适当的信息发送到服务器。

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

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

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

我试过只写没有,但在那种情况下它不读卡,而是程序选择器出现在 phone 上,或者如果 phone 没有适当的应用程序它只是说 "NFC read error"

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

Android 活动有不同的启动模式。如果您设置单个实例,它将使用已经打开的 activity 而不会创建新的 activity。您可以在覆盖方法 onNewIntent()

中阅读新意图
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  // read intent values here
}

For various activity elements

你可以使用broadcastReceiver, - 首先将接收器启动到您的 activity

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 方法中注销广播

    @Override protected void onDestroy() {

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

    }

在这样做之后而不是意图 activity 你可以 sendBroadcast()

小攻略:https://developer.android.com/reference/android/content/BroadcastReceiver.html

希望对您有所帮助