【发布时间】:2015-06-19 20:27:35
【问题描述】:
我有一个基本的 Android 应用程序,需要实现 NFC 滑动以启动特定 Activity 的功能。我通过编写Android 应用程序记录 实现了这一点。然后,我需要进一步滑动以使用相同的 Activity,而不是启动新的。
Android 应用程序记录按预期启动 Activity。然后我启动了一个创建 Pending Intent 并在 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
}
}
我的问题是系统的行为方式很奇怪。您可以使用标签启动 Activity,但第二次滑动将启动新的 Activity。然后,进一步的滑动将使用现有的 Activity,但 Intent 将始终看起来是相同的。我尝试从标签中读取文本记录,这应该会根据我滑动的标签而改变——但事实并非如此。就好像我抓取 Intent 的方法总是拾取同一个,而与滑动的标签无关。
【问题讨论】:
标签: android android-intent nfc android-applicationrecord