【发布时间】:2016-10-07 11:58:31
【问题描述】:
我试图让我的应用程序打开一个特定的片段,然后处理该片段中的标签数据。当应用程序在前台运行时它正在工作,但是当我在后台发现 TAG 时,它似乎丢失了额外的数据。
当我阅读 TAG 时,应用程序被置于前台,onNewIntent 被调用,intent action 为 android.nfc.action.TAG_DISCOVERED。但是没有intent.EXTRA_TAG,因为当我直接从前台检测到它时......我做错了什么?
这是我的代码的 NFC 特定部分:
曾经在我的活动中...
@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);
}
曾几何时在我的片段中......(当我从背景中检测到 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);
}
}
}
}
从前在清单中...
<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 并在代码 NfcAdapter.ACTION_TAG_DISCOVERED 中......太笨了
-
TAG_DISCOVERED 比 TECH_DISCOVERED 好用吗?
标签: android android-fragments android-intent nfc intentfilter