import java.io.IOException;
import java.nio.charset.Charset;
import android.content.Context;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.widget.Toast;
public class NFC {
public static boolean writeTag(Context context, Tag tag) {
NdefRecord relayRecord =
new NdefRecord(
NdefRecord.TNF_ABSOLUTE_URI ,
"zoeice://com.zoeice.example/applicationUp".getBytes(Charset.forName("US-ASCII")),
new
byte[0], new byte[0]);
// Complete NDEF message
with both records
NdefMessage message = new
NdefMessage(new NdefRecord[] {relayRecord});
try {
// If the tag is already formatted, just write
the message to it
Ndef ndef = Ndef.get(tag);
if(ndef != null) {
ndef.connect();
// Make
sure the tag is writable
if(!ndef.isWritable()) {
Toast.makeText(context, "nfcReadOnlyErrorTitle", Toast.LENGTH_SHORT
).show();
return false;
}
// Check if
there's enough space on the tag for the message
int size =
message.toByteArray().length;
if(ndef.getMaxSize() < size) {
Toast.makeText(context, "nfcReadOnlyErrorTitle", Toast.LENGTH_SHORT
).show();
return false;
}
try {
// Write the data to the
tag
ndef.writeNdefMessage(message);
Toast.makeText(context,
"nfcWrittenTitle", Toast.LENGTH_SHORT ).show();
return true;
} catch
(TagLostException tle) {
Toast.makeText(context, "nfcTagLostErrorTitle", Toast.LENGTH_SHORT
).show();
return false;
} catch
(IOException ioe) {
Toast.makeText(context, "nfcFormattingErrorTitle",
Toast.LENGTH_SHORT ).show();
return false;
} catch
(FormatException fe) {
Toast.makeText(context, "nfcFormattingErrorTitle",
Toast.LENGTH_SHORT ).show();
return false;
}
// If the tag is not formatted, format it with
the message
} else {
NdefFormatable format =
NdefFormatable.get(tag);
if(format
!= null) {
try {
format.connect();
format.format(message);
Toast.makeText(context, "nfcWrittenTitle",
Toast.LENGTH_SHORT ).show();
return true;
} catch (TagLostException tle)
{
Toast.makeText(context,
"nfcTagLostErrorTitle", Toast.LENGTH_SHORT ).show();
return false;
} catch (IOException ioe)
{
Toast.makeText(context,
"nfcFormattingErrorTitle", Toast.LENGTH_SHORT ).show();
return false;
} catch (FormatException fe)
{
Toast.makeText(context,
"nfcFormattingErrorTitle", Toast.LENGTH_SHORT ).show();
return false;
}
} else
{
Toast.makeText(context, "nfcNoNdefErrorTitle", Toast.LENGTH_SHORT
).show();
return false;
}
}
} catch(Exception e)
{
Toast.makeText(context,
"nfcUnknownErrorTitle", Toast.LENGTH_SHORT ).show();
}
return false;
}
}
识别Tag的方法是在AndroidManifest.xml中加入: