編輯:關於 Android 程式設計
最近在研究 Android 的 NFC 問題。網路上關於 Android NFC 讀寫的文章很多,但大多數都聚焦在 Mifare Classic 類型的卡,實際測試卻常不得要領。因此這裡以自己實作的一些程式碼供大家參考。
測試環境:手機為 Android 4.4 的 Google Nexus 4,NFC 卡類型為 Ultralight C。
public String readNdef(Tag tag) {
String result = null;
Ndef ndef = Ndef.get(tag);
try {
ndef.connect();
NdefMessage msg = ndef.getNdefMessage();
result = new String(msg.toByteArray());
} catch (IOException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
} finally {
try {
if (ndef != null && ndef.isConnected()) {
ndef.close();
ndef = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
對 NFC 稍有了解的人都知道,傳入的 tag 是透過 tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 取得的,這部分網路上已有大量說明,此處不再贅述。
public void writeNdef(Tag tag, String Text) {
Ndef ndef = Ndef.get(tag);
try {
ndef.connect();
byte[] data = Text.getBytes();
NdefMessage msg = new NdefMessage(new NdefRecord[] {
createMimeRecord("application/com.bjypc.han.googlejuesai", data)
});
ndef.writeNdefMessage(msg);
} catch (IOException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
} finally {
try {
if (ndef != null && ndef.isConnected()) {
ndef.close();
ndef = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
其中建立 MIME 記錄的方法如下:
public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
return mimeRecord;
}
完成以上步驟,就能成功讀取或寫入 NDEF 卡的內容了,希望對大家有幫助。
自定義控件(二):多點觸控、Matrix 變換與 FlowLayout 流式布局
多點觸控事件簡單介紹最關鍵的是 onTouchEvent 這個方法。接下來還會介紹更多與事件相關的知識(比如事件分發),這裡先聚焦最簡單的觸控事件。單指有四個動作,再加上
Android 四大元件之 Service 詳解:啟動、綁定與生命週期
Service 是 Android 四大元件之一,也是最容易觀念混淆的一個。這篇把它的定位、兩種啟動方式、生命週期回呼與通訊機制完整梳理一次。 一、Service 是什
ExpandableListView 可折疊列表與 StackView 棧式視圖用法詳解
這一節介紹兩個帶適配器的控件:ExpandableListView(可折疊列表)與 StackView(棧式視圖)。前者是 QQ 好友分組那類效果的經典實現,後者則能把一
Android Path 特殊用法:文字沿路徑、貝塞爾曲線與動態水波
Path 除了畫線與封閉圖形,還能做文字沿路徑與動態曲線等進階效果。 封閉路徑與文字 以 moveTo、lineTo、close 可畫出三角形。addCircle 可建立