如何使用NFC启动活动,然后允许在同一活动上扫描不同的标签



我有一个基本的Android应用程序,需要实现NFC滑动功能来启动特定的活动。我通过编写Android应用程序记录实现了这一点。然后我需要进一步的滑动来使用相同的活动,而不是启动新的活动。

Android应用程序记录按预期启动"活动"。然后,我启动一个创建挂起的意向,并在OnResume中设置一个前台调度

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant);
// initialize NFC
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
@Override
protected void onResume() {
Log.d(TAG, "onResume");
super.onResume();
enableForegroundMode();
doTagOperations(getIntent());
}
public void enableForegroundMode() {
Log.d(TAG, "enableForegroundMode");
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); // filter for all
IntentFilter[] writeTagFilters = new IntentFilter[] {tagDetected};
nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, writeTagFilters, null);
}

然后我有了一个方法来标记相关的活动。如下所示:

private void doTagOperations(Intent intent) {
Log.i(TAG, intent.getAction());
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
TextView textView = (TextView) findViewById(R.id.title);
textView.setText("Hello NFC!");
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages != null) {
Log.d(TAG, "Found " + messages.length + " NDEF messages"); // is almost always just one
vibrate(); // signal found messages :-)
// parse to records
for (int i = 0; i < messages.length; i++) {
try {
List<Record> records = new Message((NdefMessage)messages[i]);
Log.d(TAG, "Found " + records.size() + " records in message " + i);
for(int k = 0; k < records.size(); k++) {
Log.d(TAG, " Record #" + k + " is of class " + records.get(k).getClass().getSimpleName());
Record record = records.get(k);
if(records.get(k).getClass().getSimpleName().equals("TextRecord")) {
String plant = new String(records.get(k).getNdefRecord().getPayload());
Log.i(TAG, plant);
textView.setText(plant);
}
if(record instanceof AndroidApplicationRecord) {
AndroidApplicationRecord aar = (AndroidApplicationRecord)record;
Log.d(TAG, "Package is " + aar.getDomain() + " " + aar.getType());
}
}
} catch (Exception e) {
Log.e(TAG, "Problem parsing message", e);
}
}
}
} else {
// ignore
}
}

我的问题是,这个系统的行为方式很奇怪。您可以使用标签启动"活动",但第二次滑动将启动新的"活动"。然后,进一步的滑动将使用现有的"活动",但"意图"将始终显示为相同。我试图从标签中读取文本记录,这应该会根据我滑动的标签而改变,但事实并非如此。这就好像我获取Intent的方法总是选择相同的方法,而不管刷了什么标签。

从NFC前台调度中获取新意图

onResume()中,您可以使用getIntent()检索意图。除非用setIntent()覆盖此意图,否则getIntent()将返回最初启动活动的意图。

NFC前台调度系统的新意图通过onNewIntent()方法传递给您的活动。因此,你可以这样做:

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
doTagOperations(intent);
}

第二个NFC事件启动活动的新实例

我不太确定,但我可能想尝试为你的活动设置lauchMode。请参阅NFC标签阅读问题的答案。您也可以尝试使用前台调度系统的替代方法(使用createPendingResult()onActivityResult())是否适用于这种情况。请在此处查看我的另一个答案。

最新更新