1
我試圖做到這一點,當我打開我的應用程序並掃描一個標記時,它會顯示一個帶有標記ID的烤麪包。問題是,每次我掃描一個標籤時,它會列出一個應用程序列表,我可以在其中選擇我的應用程序。NFC前臺調度不工作
我試圖實現前臺調度機制,但它並沒有顯示任何東西(它既不崩潰,也不顯示吐司)。
這是主代碼:
public class loginPage extends AppCompatActivity {
NfcAdapter mAdapter;
PendingIntent pendingIntent;
private String serialId = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
mAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if (mAdapter == null) {
Toast.makeText(this,
"NFC NOT supported on this devices!",
Toast.LENGTH_LONG).show();
finish();
} else if (!mAdapter.isEnabled()) {
Toast.makeText(this,
"NFC NOT Enabled!",
Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onResume() {
super.onResume();
mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
@Override
public void onPause(){
super.onPause();
mAdapter.disableForegroundDispatch(this);
}
@Override
public void onNewIntent(Intent intent) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
try {
byte[] tagId = tag.getId();
serialId = toHexString(tagId);
Log.d("[ReadCardTools]", "Serial Number: " + serialId);
Toast.makeText(this, serialId, Toast.LENGTH_SHORT).show();
} catch (NullPointerException ex) {
ex.printStackTrace();
serialId = "ERROR";
}
}
}
public static String toHexString(byte[] bytes) {
char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v/16];
hexChars[j * 2 + 1] = hexArray[v % 16];
}
return new String(hexChars);
}
}
清單包含下列添加物:
<uses-permission android:name="android.permission.NFC"/>
<uses-feature android:name="android.hardware.nfc"
android:required="true"/>
和
<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_tech_filter" />
該過濾器是:
<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>
每次我掃描一個標籤時,logcat只會說「D/PersonaManager:isNFCAllowed」。
非常感謝你!這按預期工作。 –