【发布时间】:2020-10-20 08:34:30
【问题描述】:
我正在尝试在我的 Android 应用程序中读取 NFC 标签,NFC 标签是带有纯文本的简单卡片,在查看了 Android 文档并查看了一些其他指南之后,我在我的 AndroidManifest 中得到了以下代码:
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<activity
android:name=".pterm" // activity where i would be able to read NFC
android:screenOrientation="portrait"
android:theme="@style/SplashScreen">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
</intent-filter>
</activity>
在我的活动中,我添加了以下代码:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (nfcRead) {
readFromIntent(intent);
}
}
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] messages = null;
if (rawMessages != null) {
messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messages[i] = (NdefMessage) rawMessages[i];
NdefRecord[] records = messages[i].getRecords();
//if you are sure you have text then you don't need to test TNF
for(NdefRecord record: records){
processRecord(record);
}
}
}
}
}
public void processRecord(NdefRecord record) {
short tnf = record.getTnf();
switch (tnf) {
case NdefRecord.TNF_WELL_KNOWN: {
if (Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
String yourtext = processRtdTextRecord(record.getPayload());
Log.e("NFC:", yourtext);
} else if (Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
return;
} else if (Arrays.equals(record.getType(), NdefRecord.RTD_SMART_POSTER)) {
return;
} else {
return;
}
}
case NdefRecord.TNF_MIME_MEDIA: {
if (record.toMimeType().equals("MIME/Type")) {
// handle this as you want
} else {
//Record is not our MIME
}
}
// you can write more cases
default: {
//unsupported NDEF Record
}
}
}
private String processRtdTextRecord(byte[] payload) {
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
int languageCodeLength = payload[0] & 0063;
String text = "";
try {
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("UnsupportedEncoding", e.toString());
}
return text;
}
但是当我尝试读取 NFC 标签时,甚至不会触发 onNewIntent 事件,但会在设备发出 NFC 通知声音时读取 NFC。
应用程序的目的是仅在自定义 AletDialog 启动时读取 NFC,一旦 NFC 读取了值,它应该被放置在 EditText 中,并且只有在 Dialog 再次启动时才能再次读取新值.
应用程序正在使用 LockTaskMode。
【问题讨论】: