Android 如何避免启动支持NFC的应用程序?
假设我有两项活动:Android 如何避免启动支持NFC的应用程序?,android,android-intent,android-activity,nfc,Android,Android Intent,Android Activity,Nfc,假设我有两项活动: 主要活动和 第二项活动 我想要实现的是通过发现NFC标记从MainActivity传递到SecondActivity。我通过在SecondActivity标记下的清单中添加意图过滤器来实现这一点 但我的问题是,即使应用程序被杀死,应用程序也会启动并进入第二个活动。基本上,我希望标记发现只在我处于主活动中时发生(在单击按钮开始阅读之后) 我尝试在MainActivity的onCreate()方法中以编程方式添加意图过滤器,并重写onNewIntent()方法,但没有成功 我还尝
onCreate()
方法中以编程方式添加意图过滤器,并重写onNewIntent()
方法,但没有成功
我还尝试将启动模式设置为“singleTop”,但没有成功
以下是我添加到MainActivity的onCreate()
方法中的内容:
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意向后,您可以启动SecondActivity
并将意向传递给它:
@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);
}
}
如果我正确理解了您的问题,那么问题在于,当应用程序未运行时,您的活动也会触发 如果这就是问题所在,那么问题在于您已经在AndroidManifest.xml文件中声明您的活动将在NFC事件时触发,解决方案是从清单中的活动声明中删除NFC块