1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
|
package com.dirix.leavemessage;
import java.io.IOException;
import java.nio.charset.Charset;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
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.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private NfcAdapter mNfcAdapter;
private IntentFilter[] mWriteTagFilters;
private PendingIntent mNfcPendingIntent;
private boolean writeProtect = false;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
IntentFilter discovery = new IntentFilter(
NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(
NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED);
// Intent filters for writing to a tag
mWriteTagFilters = new IntentFilter[] { discovery };
}
protected void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled()) {
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mWriteTagFilters, null);
}
} else {
Toast.makeText(context, "Sorry, No NFC Adapter found.",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
//getting id of the tag
// validate that this tag can be written
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (supportedTechs(detectedTag.getTechList())) {
// check if tag is writable (to the extent that we can
if (writableTag(detectedTag)) {
// writeTag here
WriteResponse wr = writeTag(getTagAsNdef(), detectedTag);
String message = (wr.getStatus() == 1 ? "Success: "
: "Failed: ") + wr.getMessage();
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "This tag is not writable",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "This tag type is not supported",
Toast.LENGTH_SHORT).show();
}
}
}
public WriteResponse writeTag(NdefMessage message, Tag tag) {
int size = message.toByteArray().length;
String mess = "";
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
return new WriteResponse(0, "Tag is read-only");
}
if (ndef.getMaxSize() < size) {
mess = "Tag capacity is " + ndef.getMaxSize()
+ " bytes, message is " + size + " bytes.";
return new WriteResponse(0, mess);
}
ndef.writeNdefMessage(message);
if (writeProtect)
ndef.makeReadOnly();
mess = "Wrote message to pre-formatted tag.";
return new WriteResponse(1, mess);
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
mess = "Formatted tag and wrote message";
return new WriteResponse(1, mess);
} catch (IOException e) {
mess = "Failed to format tag.";
return new WriteResponse(0, mess);
}
} else {
mess = "Tag doesn't support NDEF.";
return new WriteResponse(0, mess);
}
}
} catch (Exception e) {
mess = "Failed to write tag";
return new WriteResponse(0, mess);
}
}
private class WriteResponse {
int status;
String message;
WriteResponse(int Status, String Message) {
this.status = Status;
this.message = Message;
}
public int getStatus() {
return status;
}
public String getMessage() {
return message;
}
}
public static boolean supportedTechs(String[] techs) {
boolean ultralight = false;
boolean nfcA = false;
boolean ndef = false;
for (String tech : techs) {
if (tech.equals("android.nfc.tech.MifareUltralight")) {
ultralight = true;
} else if (tech.equals("android.nfc.tech.NfcA")) {
nfcA = true;
} else if (tech.equals("android.nfc.tech.Ndef")
|| tech.equals("android.nfc.tech.NdefFormatable")) {
ndef = true;
}
}
if (ultralight && nfcA && ndef) {
return true;
} else {
return false;
}
}
private boolean writableTag(Tag tag) {
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
Toast.makeText(context, "Tag is read-only.",
Toast.LENGTH_SHORT).show();
ndef.close();
return false;
}
ndef.close();
return true;
}
} catch (Exception e) {
Toast.makeText(context, "Failed to read tag", Toast.LENGTH_SHORT)
.show();
}
return false;
}
private NdefMessage getTagAsNdef() {
boolean addAAR = false;
EditText textView = (EditText)findViewById(R.id.message);
String uniqueId = textView.getEditableText().toString();
byte[] uriField = uniqueId.getBytes(Charset.forName("US-ASCII"));
byte[] payload = new byte[uriField.length + 1]; // add 1 for the URI
// Prefix
payload[0] = 0x01; // prefixes http://www. to the URI
System.arraycopy(uriField, 0, payload, 0, uriField.length); // appends
// URI to
// payload
NdefRecord rtdUriRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], payload);
if (addAAR) {
// note: returns AAR for different app (nfcreadtag)
return new NdefMessage(new NdefRecord[] { rtdUriRecord,
NdefRecord.createApplicationRecord("com.dirix.leavemessage") });
} else {
return new NdefMessage(new NdefRecord[] { rtdUriRecord });
}
}
} |