private void readTag(Tag t) { // get NDEF tag details Ndef ndefTag = Ndef.get(t); // get NDEF message details NdefMessage ndefMesg = ndefTag.getCachedNdefMessage(); if (ndefMesg == null) { return; } NdefRecord[] ndefRecords = ndefMesg.getRecords(); if (ndefRecords == null) { return; } for (NdefRecord record : ndefRecords) { short tnf = record.getTnf(); String type = new String(record.getType()); if (tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(type.getBytes(), NdefRecord.RTD_URI)) { String url = new String(record.getPayload()); if (url.startsWith(ATTENDEE_URL_PREFIX)) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://" + url.substring(1))); startActivity(i); return; } } } }
private void processIntent(Intent intent) { Log.d("ANDROID_LAB", "processIntent..."); Bitmap bitmap = null; Parcelable[] ndefMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (ndefMsgs != null) { Log.d("ANDROID_LAB", "ndefMsgs.size=" + ndefMsgs.length); String str = ""; for (int i = 0; i < ndefMsgs.length; i++) { NdefMessage msg = (NdefMessage) ndefMsgs[i]; NdefRecord[] records = msg.getRecords(); if (records != null) { Log.d("ANDROID_LAB", "records.size=" + records.length); for (int k = 0; k < records.length; k++) { NdefRecord record = records[k]; byte[] data = record.getPayload(); if (data != null) { if (k == 0) { str += new String(data); } else if (k == 1) { bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } } } } txtPushContent.setText(str); if (bitmap != null) { txtPushContent.setCompoundDrawablesWithIntrinsicBounds( null, null, null, new BitmapDrawable(bitmap)); } } }
/** * Return the length of this NDEF Message if it is written to a byte array with {@link * #toByteArray}. * * <p>An NDEF Message can be formatted to bytes in different ways depending on chunking, SR, and * ID flags, so the length returned by this method may not be equal to the length of the original * byte array used to construct this NDEF Message. However it will always be equal to the length * of the byte array produced by {@link #toByteArray}. * * @return length of this NDEF Message when written to bytes with {@link #toByteArray} * @see #toByteArray */ public int getByteArrayLength() { int length = 0; for (NdefRecord r : mRecords) { length += r.getByteLength(); } return length; }
/** * Method to send the messages over another device * * @param NfcIntent - NFC intent to pass data */ private void handleNfcIntent(Intent NfcIntent) { if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(NfcIntent.getAction())) { Parcelable[] receivedArray = NfcIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (receivedArray != null) { messagesToReceiveQueue.clear(); NdefMessage receivedMessage = (NdefMessage) receivedArray[0]; NdefRecord[] linkRecords = receivedMessage.getRecords(); for (NdefRecord record : linkRecords) { String message = new String(record.getPayload()); if (!message.equals(getPackageName())) { messagesToReceiveQueue.add(message); } } Toast.makeText( this, "Total " + messagesToReceiveQueue.size() + "Messages received", Toast.LENGTH_LONG) .show(); updateTextViews(); } else { Toast.makeText(this, "Received Blank", Toast.LENGTH_LONG).show(); } } }
void processIntent(Intent intent) throws UnsupportedEncodingException { Parcelable[] msgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage[] nmsgs = new NdefMessage[msgs.length]; for (int i = 0; i < msgs.length; i++) { nmsgs[i] = (NdefMessage) msgs[i]; } NdefRecord record = nmsgs[0].getRecords()[0]; byte[] payload = record.getPayload(); if (payload != null) { if (nmsgs[0].getRecords()[0].getTnf() != 2) { // Toast.makeText(this, "New Text received!", Toast.LENGTH_SHORT) // .show(); // String message = String.valueOf(record.getPayload()); String message = getTextData(record.getPayload()); // textview = (TextView) findViewById(R.id.textView2); // Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); // text = String.valueOf(payload); // textview.setText(message); Intent intent_nfccode = new Intent(this, Details_page.class); intent_nfccode.putExtra("NFC Code", message); startActivity(intent_nfccode); } } }
@Override public NdefMessage createNdefMessage(NfcEvent event) { Log.d("ANDROID_LAB", "createNdefMessage thread.name=" + Thread.currentThread().getName()); StringBuilder sb = new StringBuilder(); sb.append(Build.MODEL + "("); // 手机型号 sb.append(Build.VERSION.SDK_INT + ","); // SDK版本号 sb.append(Build.VERSION.RELEASE + ")"); // Firmware/OS 版本号 sb.append("发送来一条NFC消息, 时间是"); Time time = new Time(); time.setToNow(); sb.append(time.format("%H:%M:%S")); Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.and); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] bmpData = baos.toByteArray(); NdefRecord[] records = new NdefRecord[2]; records[0] = NdefRecord.createMime("application/lab.sodino.nfc", sb.toString().getBytes()); // 文本消息 records[1] = NdefRecord.createMime("application/lab.sodino.nfc", bmpData); // 图片消息 // records[2] = NdefRecord.createApplicationRecord("com.tencent.mobileqq"); NdefMessage msg = new NdefMessage(records); return msg; }
@Override protected String doInBackground(Tag... params) { Tag tag = params[0]; Ndef ndef = Ndef.get(tag); if (ndef == null) { // NDEF is not supported by this Tag. return null; } NdefMessage ndefMessage = ndef.getCachedNdefMessage(); NdefRecord[] records = ndefMessage.getRecords(); for (NdefRecord ndefRecord : records) { if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) { try { return readText(ndefRecord); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Unsupported Encoding", e); } } } return null; }
/** Parse an well known URI record */ private static UriRecord parseWellKnown(NdefRecord record) { Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_URI)); byte[] payload = record.getPayload(); String prefix = URI_PREFIX_MAP.get(payload[0]); byte[] fullUri = Bytes.concat( prefix.getBytes(Charset.forName("UTF-8")), Arrays.copyOfRange(payload, 1, payload.length)); Uri uri = Uri.parse(new String(fullUri, Charset.forName("UTF-8"))); return new UriRecord(uri); }
@Override public NdefMessage createNdefMessage(final NfcEvent event) { NdefRecord[] records; if (mPermalink == null) { // no permalink yet, just provide AAR records = new NdefRecord[] {NdefRecord.createApplicationRecord(getPackageName())}; } else { records = new NdefRecord[] { NdefRecord.createUri(mPermalink), NdefRecord.createApplicationRecord(getPackageName()) }; } return new NdefMessage(records); }
private ScanableTag messageToScanable(NdefMessage message) { NdefRecord record = message.getRecords()[0]; // XXX Ignoring the first byte because it contains a flag we are not // paying attention to yet byte[] rawData = new byte[record.getPayload().length - 1]; System.arraycopy(record.getPayload(), 1, rawData, 0, rawData.length); String text = decodePayload(rawData); String mimeType = decodePayload(record.getType()); return new TagParser().parse(mimeType, text); }
private void printMessage(NdefRecord record) { byte[] id; // Id of the record short tnf; // TNF: See android.nfc.NdefRecord byte[] payload; // Payload of the record (the actual message) String finalMessage, id_string; id = record.getId(); tnf = record.getTnf(); payload = record.getPayload(); id_string = DataConversion.bytesToASCIIString(id); receiveTab.append("\nID is " + id_string); receiveTab.append("\nTNF is " + tnf); finalMessage = DataConversion.bytesToASCIIString(payload); receiveTab.append("\n" + finalMessage + "\n"); }
@Override public boolean supportsRequest(NdefRecord handoverRequest) { if (handoverRequest.getTnf() != NdefRecord.TNF_ABSOLUTE_URI || !Arrays.equals(handoverRequest.getType(), NdefRecord.RTD_URI)) { return false; } String uriString = new String(handoverRequest.getPayload()); if (uriString.startsWith(BT_SOCKET_SCHEMA)) { return true; } return false; }
public static String parse(NdefRecord record) { try { byte[] payload = record.getPayload(); /* * payload[0] contains the "Status Byte Encodings" field, per the * NFC Forum "Text Record Type Definition" section 3.2.1. * * bit7 is the Text Encoding Field. * * if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1): * The text is encoded in UTF16 * * Bit_6 is reserved for future use and must be set to zero. * * Bits 5 to 0 are the length of the IANA language code. */ String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16"; int languageCodeLength = payload[0] & 0077; String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII"); String text = new String( payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding); return text; } catch (UnsupportedEncodingException e) { // should never happen unless we get a malformed tag. throw new IllegalArgumentException(e); } }
private String readText(NdefRecord record) throws UnsupportedEncodingException { /* * See NFC forum specification for "Text Record Type Definition" at 3.2.1 * * http://www.nfc-forum.org/specs/ * * bit_7 defines encoding * bit_6 reserved for future use, must be 0 * bit_5..0 length of IANA language code */ byte[] payload = record.getPayload(); // Get the Text Encoding String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Language Code int languageCodeLength = payload[0] & 0063; // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII"); // e.g. "en" // Get the Text return new String( payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding); }
public static String[] readStrings(Tag tag) throws IOException, FormatException, NotReadableException { Ndef ndefTag = Ndef.get(tag); if (ndefTag == null) { throw new NotReadableException("The tag doesn't support Ndef tech"); } ndefTag.connect(); NdefMessage message = ndefTag.getNdefMessage(); NdefRecord[] records = message.getRecords(); String[] out = new String[records.length]; int i = 0; for (NdefRecord rec : records) { out[i++] = new String(rec.getPayload(), Charset.forName("UTF-8")); } ndefTag.close(); return out; }
@Override protected void onHandleIntent(Intent intent) { intent = (Intent) intent.getExtras().get(NFC_INTENT); TimeloggerDatabaseOpenHelper databaseOpenHelper = new TimeloggerDatabaseOpenHelper(getApplicationContext()); Log.d(NFC_TIMELOGGER, "handling following intent in service: " + intent.getAction()); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { Parcelable[] ndefMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (ndefMessages != null) { NdefMessage[] msgs = new NdefMessage[ndefMessages.length]; for (int i = 0; i < ndefMessages.length; i++) { msgs[i] = (NdefMessage) ndefMessages[i]; NdefRecord[] records = msgs[i].getRecords(); for (NdefRecord ndefRecord : records) { String payload = new String(ndefRecord.getPayload()); Log.d(NFC_TIMELOGGER, payload); NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); String resultAction = databaseOpenHelper.handleCategory(payload); Notification notification = new Notification.Builder(this) .setContentTitle("Timelogger") .setTicker(resultAction + payload) .setContentText(payload) .setSmallIcon(R.drawable.ic_launcher) .build(); notifManager.notify(1234, notification); Log.d(NFC_TIMELOGGER, "notification sent"); Intent updateIntent = new Intent("FRAGMENT_UPDATE"); this.sendBroadcast(updateIntent); } } } } databaseOpenHelper.close(); }
public NdefMessage createNdefMessage() { return new NdefMessage( new NdefRecord[] { createMime( Constants.TAG_WRITER_MIME_TYPE, new Gson().toJson(createdDrinkerFromUserInput()).getBytes()), NdefRecord.createApplicationRecord(Constants.DRINKER_STATION_APP_RECORD) }); }
public static UriRecord parse(NdefRecord record) { short tnf = record.getTnf(); if (tnf == NdefRecord.TNF_WELL_KNOWN) { return parseWellKnown(record); } else if (tnf == NdefRecord.TNF_ABSOLUTE_URI) { return parseAbsolute(record); } throw new IllegalArgumentException("Unknown TNF " + tnf); }
private void processIntent(Intent intent) { Parcelable[] ndefMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) ndefMessages[0]; NdefRecord[] records = msg.getRecords(); for (NdefRecord record : records) { String dataString = new String(record.getPayload()); Scanner scanner = new Scanner(dataString); DataContainer dataContainer = new DataContainer(); for (int i = 0; i < Constants.DATA_NAMES.length; i++) { if (Constants.DATA_FIELDS[i].equals("int")) { dataContainer.setData(Constants.DATA_NAMES[i], scanner.nextInt()); } else { dataContainer.setData(Constants.DATA_NAMES[i], scanner.nextInt() == 1); } } mDBHelper.insertDataContainer(dataContainer); } }
/** * Construct an NDEF Message by parsing raw bytes. * * <p>Strict validation of the NDEF binary structure is performed: there must be at least one * record, every record flag must be correct, and the total length of the message must match the * length of the input data. * * <p>This parser can handle chunked records, and converts them into logical {@link NdefRecord}s * within the message. * * <p>Once the input data has been parsed to one or more logical records, basic validation of the * tnf, type, id, and payload fields of each record is performed, as per the documentation on on * {@link NdefRecord#NdefRecord(short, byte[], byte[], byte[])} * * <p>If either strict validation of the binary format fails, or basic validation during record * construction fails, a {@link FormatException} is thrown * * <p>Deep inspection of the type, id and payload fields of each record is not performed, so it is * possible to parse input that has a valid binary format and confirms to the basic validation * requirements of {@link NdefRecord#NdefRecord(short, byte[], byte[], byte[])}, but fails more * strict requirements as specified by the NFC Forum. * * <p class="note">It is safe to re-use the data byte array after construction: this constructor * will make an internal copy of all necessary fields. * * @param data raw bytes to parse * @throws FormatException if the data cannot be parsed */ public NdefMessage(byte[] data) throws FormatException { if (data == null) throw new NullPointerException("data is null"); ByteBuffer buffer = ByteBuffer.wrap(data); mRecords = NdefRecord.parse(buffer, false); if (buffer.remaining() > 0) { throw new FormatException("trailing data"); } }
/** * Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is an NFC * intent that the app recognizes. If it is, then parse the NFC message and set the activity's * intent (using {@link android.app.Activity#setIntent(android.content.Intent)}) to something the * app can recognize (i.e. a normal {@link android.content.Intent#ACTION_VIEW} intent). */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public static void tryUpdateIntentFromBeam(Activity activity) { if (UIUtils.hasICS()) { Intent originalIntent = activity.getIntent(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) { Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; // Record 0 contains the MIME type, record 1 is the AAR, if present. // In iosched, AARs are not present. NdefRecord mimeRecord = msg.getRecords()[0]; if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(new String(mimeRecord.getType()))) { // Re-set the activity's intent to one that represents session details. Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(new String(mimeRecord.getPayload()))); activity.setIntent(sessionDetailIntent); } } } }
@Override public NdefMessage createNdefMessage(NfcEvent event) { if (mInvoice != null && mInvoice.getPaymentUrls() != null && mInvoice.getPaymentUrls().getBIP72b() != null) { return new NdefMessage( new NdefRecord[] {NdefRecord.createUri(mInvoice.getPaymentUrls().getBIP72())}); } return null; }
@Override public NdefMessage createNdefMessage(NfcEvent event) { // android.os.Build.SERIAL is sent to the other device to be paired String text = (android.os.Build.SERIAL + "," + userName); NdefMessage msg = new NdefMessage( new NdefRecord[] { createMimeRecord("application/edu.temple.encryptedfiletransfer", text.getBytes()), NdefRecord.createApplicationRecord("edu.temple.encryptedfiletransfer") }); return msg; }
public String getTextFromNdefRecord(NdefRecord ndefRecord) { String tagContent = null; try { byte[] payload = ndefRecord.getPayload(); String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; int languageSize = payload[0] & 0063; tagContent = new String(payload, languageSize + 1, payload.length - languageSize - 1, textEncoding); } catch (UnsupportedEncodingException e) { Log.e("getTextFromNdefRecord", e.getMessage(), e); } return tagContent; }
/** * Creates records to send to another device if detected those records are about to send to * another device * * @return NdefRecord[] - array of records to attach */ public NdefRecord[] createRecords() { NdefRecord[] records = new NdefRecord[messagesToSendQueue.size()]; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { for (int counter = 0; counter < messagesToSendQueue.size(); counter++) { byte[] payload = messagesToSendQueue.get(counter).getBytes(Charset.forName("UTF-8")); NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload); records[counter] = record; } } else { for (int counter = 0; counter < messagesToSendQueue.size(); counter++) { byte[] payload = messagesToSendQueue.get(counter).getBytes(Charset.forName("UTF-8")); NdefRecord record = NdefRecord.createMime("text/plain", payload); records[counter] = record; } } records[messagesToSendQueue.size()] = NdefRecord.createApplicationRecord(getPackageName()); return records; }
private String readText(NdefRecord record) throws UnsupportedEncodingException { byte[] payload = record.getPayload(); // Get the Text Encoding String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Language Code int languageCodeLength = payload[0] & 0063; // Get the Text return new String( payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding); }
@Override public NdefMessage createNdefMessage(NfcEvent arg0) { NdefRecord uriRecord = new NdefRecord( NdefRecord.TNF_MIME_MEDIA, MIME_TYPE.getBytes(Charset.forName("US-ASCII")), new byte[0], beamFragment.getUrl().getBytes(Charset.forName("US-ASCII"))); NdefMessage msg = new NdefMessage( new NdefRecord[] { uriRecord, NdefRecord.createApplicationRecord("com.commonsware.android.webbeam") }); return (msg); }
/* Called when the activity will start interacting with the user. */ @Override protected void onResume() { super.onResume(); // Double check if NFC is enabled checkNfcEnabled(); Log.d(TAG, "onResume: " + getIntent()); if (getIntent().getAction() != null) { // tag received when app is not running and not in the foreground: if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { NdefMessage[] msgs = getNdefMessagesFromIntent(getIntent()); NdefRecord record = msgs[0].getRecords()[0]; byte[] payload = record.getPayload(); setTextFieldValues(new String(payload)); } } // Enable priority for current activity to detect scanned tags // enableForegroundDispatch( activity, pendingIntent, // intentsFiltersArray, techListsArray ); mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, mReadTagFilters, null); }
private String readText(NdefRecord record) throws UnsupportedEncodingException { byte[] payload = record.getPayload(); String textEncoding; if ((payload[0] & 128) == 0) { textEncoding = "UTF-8"; } else { textEncoding = "UTF-16"; } int languageCodeLength = payload[0] & 0063; return new String( payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding); }
@Override protected void onResume() { super.onResume(); Intent intent = getIntent(); String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { NdefMessage[] msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; for (NdefRecord record : msgs[i].getRecords()) { String type = new String(record.getType()); byte[] payload = record.getPayload(); if (PROFILE_MIME_TYPE.equals(type) && payload != null && payload.length == 16) { handleProfileMimeType(payload); } } } } } finish(); }