我正在尝试让我的应用程序打开一个特定的片段,然后处理该片段中的标签数据。当应用程序在前台运行时,它正在工作,但是当我在背景上发现TAG时,它似乎丢失了它的额外数据。
当我阅读TAG时,应用程序被置于前台,{{1>}被调用,意图行动为onNewIntent
。但是当我直接从前台检测到它时,没有android.nfc.action.TAG_DISCOVERED
......我做错了什么?
以下是我的代码的NFC特定部分:
从事我的活动......
intent.EXTRA_TAG
我的片段中的一次...... (当我从背景中检测到TAG时,永远不会输入for循环)
@Override
public void onNewIntent(Intent intent) {
Log.e(TAG, "RETRIVE HERE" + selectedFragment.getTagText() );
if (selectedFragment instanceof FragmentNfc) {
Log.e(TAG, "RETRIVE HERE");
FragmentNfc my = (FragmentNfc) selectedFragment;
my.processNFC(intent);
}
}
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
adapter.enableForegroundDispatch(activity, pendingIntent, null, null);
}
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
从前在Manifest中......
public void processNFC(Intent intent) {
Log.e(TAG, "Process NFC");
String hexdump = "";
String action = intent.getAction();
Log.e(TAG, "ACTION: " + action);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String[] techList = tag.getTechList();
String searchedTech = Ndef.class.getName();
for (String tech : techList) {
Log.e(TAG, "TECH: " + tech);
if (searchedTech.equals(tech)) {
byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
for (int i = 0; i < tagId.length; i++) {
String x = Integer.toHexString(((int) tagId[i] & 0xff));
if (x.length() == 1) {
x = '0' + x;
}
hexdump += x;
if (i < 6) {
hexdump += ":";
}
}
onNfcReceive(hexdump);
}
}
}
}
答案 0 :(得分:1)
由于您在清单中注册了操作android.nfc.action.TECH_DISCOVERED
的意图过滤器,因此方法onNewIntent()
将获得TECH_DISCOVERED
意图而非TAG_DISCOVERED
意图。因此,if-branch的条件
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
将评估为false,您将永远不会输入而不是分支。
您可以检查TAG_DISCOVERED
和TECH_DISCOVERED
:
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) ||
NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {