我试图让我的应用程序打开一个特定的 fragment ,然后处理该 fragment 中的标签数据。当应用程序在前台运行时它可以工作,但是当我在后台发现 TAG 时,它似乎丢失了它的额外数据。
当我读取 TAG 时,应用程序被置于前台,onNewIntent
被调用,intent 操作 为 android.nfc.action.TAG_DISCOVERED
。但是没有 intent.EXTRA_TAG
当我直接从前景检测到它时......我做错了什么?
这是我的代码的 NFC 特定部分:
从前在我的 Activity 中...
@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);
}
从前在我的 fragment 中...(当我从后台检测到 TAG 时,永远不会进入 for 循环)
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);
}
}
}
}
从前在 list 中...
<activity
android:name=".activityv2.ActivityHome"
android:label="Security Agent"
android:launchMode="singleInstance"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tag_filter" />
</activity>
最佳答案
自从您为操作注册了意向过滤器 android.nfc.action.TECH_DISCOVERED
在您的 list 中,方法 onNewIntent()
将收到 <b>TECH</b>_DISCOVERED
Intent 而不是 <b>TAG</b>_DISCOVERED
Intent 。因此,if 分支的条件
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)) {
关于android - 当在后台从应用程序中发现时,NFC 标签的 Intent 会额外丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37681785/