我正在开发一款Android应用程序,它的功能是从NFC卡读取NFC-Tag ID。我正在使用以下代码从卡上读取NFC标签。
@Override
protected void onNewIntent(Intent intent) {
ReadNFCTagFromIntent(intent);
}
private void ReadNFCTagFromIntent(Intent intent) {
byte[] inarray = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
int i, j, in;
String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F" };
String nfc_card_tag = "";
for (j = 0; j < inarray.length; ++j) {
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
nfc_card_tag += hex[i];
i = in & 0x0f;
nfc_card_tag += hex[i];
}
ShowDialog(nfc_card_tag); // This function Will Display a Dialog With Tag Value....
}
我还在活动中配置了Foreground Dispatch System OnPause&amp; OnResume活动方法
@Override
protected void onResume() {
super.onResume();
try {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent,
new IntentFilter[] { filter }, this.techList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
try {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.disableForegroundDispatch(this);
} catch (Exception e) {
}
}
这是清单文件中的我的活动声明
<activity android:name="ActHome"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/nfctechlist" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
</intent-filter>
这是我用于“TECH_DISCOVERED”的资源文件中的xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.IsoDep</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcB</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcF</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcV</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.Ndef</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NdefFormatable</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
</resources>
此代码工作正常,但问题是当我尝试将nfc-card连接到我的设备时,我的活动挂起/冻结至少10/15秒,然后根据我的代码显示Dialog。如果我尝试连续连续添加5到6张卡片,那么它会在10-15秒后同时显示所有对话框。我不知道为什么我的活动在从NFC卡读取标签时挂起。
先谢谢