編輯:關於 Android 程式設計
這篇記錄一個以 NFC 寫入並讀取校園卡資訊的小範例。核心是利用 NfcAdapter 的前台分發(Foreground Dispatch)機制攔截標籤事件,再把學號與姓名封裝成 NDEF 外部型別記錄寫進卡片。
package com.nfclab.stuCard;
import java.io.IOException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class stuCardActivity extends Activity {
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
private String studentId = "";
private String studentName = " ";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText studentIdEditText = (EditText) this.findViewById(R.id.studentIdEditText);
final EditText studentNameEditText = (EditText) this.findViewById(R.id.studentNameEditText);
Button writeStudentButton = (Button) this.findViewById(R.id.writeStudentButton);
writeStudentButton.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View view) {
studentId = studentIdEditText.getText().toString();
studentName = studentNameEditText.getText().toString();
TextView messageText = (TextView) findViewById(R.id.messageText);
messageText.setText("Touch NFC Tag to write \n");
messageText.append("Student id:" + studentId
+ "\nStudent Name: " + studentName);
}
});
Button exitButton = (Button) findViewById(R.id.exitButton);
exitButton.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilters = new IntentFilter[] { ndef };
mTechLists = new String[][] {
new String[] { Ndef.class.getName() },
new String[] { NdefFormatable.class.getName() } };
}
@Override
public void onResume() {
super.onResume();
// 前台分發必須在 onResume 啟用,onPause 停用
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
}
}
@Override
public void onNewIntent(Intent intent) {
Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String externalType = "nfclab.com:transport";
String payload = studentId + ":" + studentName;
NdefRecord extRecord1 = new NdefRecord(NdefRecord.TNF_EXTERNAL_TYPE,
externalType.getBytes(), new byte[0], payload.getBytes());
NdefMessage newMessage = new NdefMessage(new NdefRecord[] { extRecord1 });
writeNdefMessageToTag(newMessage, tag);
}
@Override
public void onPause() {
super.onPause();
mNfcAdapter.disableForegroundDispatch(this);
}
/** 寫入 NDEF 訊息,若卡片尚未格式化則先格式化 */
boolean writeNdefMessageToTag(NdefMessage message, Tag detectedTag) {
int size = message.toByteArray().length;
try {
Ndef ndef = Ndef.get(detectedTag);
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
Toast.makeText(this, "Tag is read-only.", Toast.LENGTH_SHORT).show();
return false;
}
if (ndef.getMaxSize() < size) {
Toast.makeText(this, "The data cannot written to tag, Tag capacity is "
+ ndef.getMaxSize() + " bytes, message is " + size + " bytes.",
Toast.LENGTH_SHORT).show();
return false;
}
ndef.writeNdefMessage(message);
ndef.close();
Toast.makeText(this, "Message is written tag.", Toast.LENGTH_SHORT).show();
return true;
} else {
NdefFormatable ndefFormat = NdefFormatable.get(detectedTag);
if (ndefFormat != null) {
try {
ndefFormat.connect();
ndefFormat.format(message);
ndefFormat.close();
Toast.makeText(this, "The data is written to the tag ",
Toast.LENGTH_SHORT).show();
return true;
} catch (IOException e) {
Toast.makeText(this, "Failed to format tag", Toast.LENGTH_SHORT).show();
return false;
}
} else {
Toast.makeText(this, "NDEF is not supported", Toast.LENGTH_SHORT).show();
return false;
}
}
} catch (Exception e) {
Toast.makeText(this, "Write opreation is failed", Toast.LENGTH_SHORT).show();
}
return false;
}
}
用 GridLayout 排兩欄,左邊是提示文字,右邊是輸入框,下方放訊息區與兩個按鈕。
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:columnCount="2"
android:orientation="horizontal"
android:rowCount="5" >
<TextView
android:id="@+id/requestStudentId"
android:layout_row="0"
android:layout_column="0"
android:text="@string/requestStudentIdText"
android:textSize="16sp" />
<EditText
android:id="@+id/studentIdEditText"
android:layout_row="0"
android:layout_column="1"
android:inputType="text"
android:text="@string/emptyText" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/requestName"
android:layout_row="1"
android:layout_column="0"
android:text="@string/requestStudentNameText"
android:textSize="16sp" ></TextView>
<EditText
android:id="@+id/studentNameEditText"
android:layout_row="1"
android:layout_column="1"
android:inputType="text"
android:text="@string/emptyText" >
</EditText>
<TextView
android:id="@+id/messageText"
android:layout_row="3"
android:layout_column="0"
android:layout_columnSpan="2"
android:gravity="left"
android:text="@string/emptyText"
android:textSize="24sp" />
<Button
android:id="@+id/writeStudentButton"
android:layout_row="2"
android:layout_column="0"
android:gravity="left"
android:text="@string/writeButtonText" />
<Button
android:id="@+id/exitButton"
android:layout_row="2"
android:layout_column="1"
android:gravity="left"
android:text="@string/exitButtonText" />
</GridLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.nfclab.transportationwriter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.NFC" />
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</manifest>
onResume 啟用、onPause 停用,否則會有非前台時機漏事件的問題。isWritable() 與 getMaxSize(),卡片唯讀或容量不足是最常見的失敗原因。Ndef.get() 回傳 null,代表卡片尚未格式化,此時要改用 NdefFormatable 走格式化流程。
Android 傳感器詳解(二)—— 常見傳感器一覽
本文盤點幾類常見的 Android 傳感器: 方向傳感器 Orientation(如今幾乎不再單獨使用,因為嚴格意義上並不存在真正的「方向傳感器」)、磁場傳
Android Drawable 進階用法:自定義 Drawable、自定義 State 與效能優化
一、概述 Drawable 在日常開發裡幾乎無所不在,而且真的很好用。它是什麼?一句話——能畫在 Canvas 上的東西。相比 View,它不必操心 measure 與
安卓基礎學習(一):開發環境建置與第一個 HelloWorld
在動手建置 Android 開發環境之前,先花點時間認識一下 Android 本身:它以 Java 為主要開發語言,核心基於 Linux,屬於自由且開放原始碼的作業系統,
Android 照片塗鴉功能:原理與座標映射詳解
「在照片上隨手塗畫」是社群類產品常見的互動功能。看起來只是畫線,但要做到「在圖片的正確位置上,並且縮放平移之後仍然對得上」,就牽涉到矩陣變換與座標系映射。本文把整個實作拆