android.nfc.NdefRecord Java Examples

The following examples show how to use android.nfc.NdefRecord. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Message.java    From effective_android_sample with Apache License 2.0 7 votes vote down vote up
/**
 * {@link Parcelable} array constructor. If multiple messages, records are added in natural order.
 * 
 * @param messages {@link NdefMessage}s in {@link Parcelable} array.
 * @throws FormatException if known record type cannot be parsed
 */

public Message(Parcelable[] messages) throws FormatException {
    for (int i = 0; i < messages.length; i++) {
    	NdefMessage message = (NdefMessage) messages[i];
        
		for(NdefRecord record : message.getRecords()) {
			add(Record.parse(record));
		}
    }
}
 
Example #2
Source File: NfcTypeConverter.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Converts mojo NfcRecord to android.nfc.NdefRecord
 */
private static NdefRecord toNdefRecord(NfcRecord record) throws InvalidNfcMessageException,
                                                                IllegalArgumentException,
                                                                UnsupportedEncodingException {
    switch (record.recordType) {
        case NfcRecordType.URL:
            return NdefRecord.createUri(new String(record.data, getCharset(record)));
        case NfcRecordType.TEXT:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                return NdefRecord.createTextRecord(
                        "en-US", new String(record.data, getCharset(record)));
            } else {
                return NdefRecord.createMime(TEXT_MIME, record.data);
            }
        case NfcRecordType.JSON:
        case NfcRecordType.OPAQUE_RECORD:
            return NdefRecord.createMime(record.mediaType, record.data);
        default:
            throw new InvalidNfcMessageException();
    }
}
 
Example #3
Source File: CardboardDeviceParams.java    From Cardboard with Apache License 2.0 6 votes vote down vote up
private boolean parseNfcUri(NdefRecord record) {
	Uri uri = record.toUri();
	if (uri == null) {
		return false;
	}
	if (uri.getHost().equals("v1.0.0")) {
		this.mVendor = "com.google";
		this.mModel = "cardboard";
		this.mVersion = "1.0";
		return true;
	}
	List<String> segments = uri.getPathSegments();
	if (segments.size() != 2) {
		return false;
	}
	this.mVendor = uri.getHost();
	this.mModel = ((String) segments.get(0));
	this.mVersion = ((String) segments.get(1));

	return true;
}
 
Example #4
Source File: SmartPosterRecord.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
@Override
public NdefRecord getNdefRecord() {
	Message message = new Message();
	if (hasTitle()) {
		message.add(title);
	}
	if (hasUri()) {
		message.add(uri);
	}
	if (hasAction()) {
		message.add(action);
	}
	
	return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_SMART_POSTER, id != null ? id : EMPTY, message.getNdefMessage().toByteArray());
	
}
 
Example #5
Source File: GenericControlRecord.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
@Override
public NdefRecord getNdefRecord() {
	if(!hasTarget()) {
		throw new IllegalArgumentException("Expected target");
	}
	
	List<NdefRecord> records = new ArrayList<NdefRecord>();
	records.add(target.getNdefRecord());
	
	if (hasAction()) {
		records.add(action.getNdefRecord());
	}
	
	if (hasData()) {
		records.add(data.getNdefRecord());
	}
	
	byte[] array = new NdefMessage(records.toArray(new NdefRecord[records.size()])).toByteArray();
	
	byte[] payload = new byte[array.length + 1];
	payload[0] = configurationByte;
	System.arraycopy(array, 0, payload, 1, array.length);
	
	return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, type, id != null ? id : EMPTY, payload);
}
 
Example #6
Source File: WriteTextActivity.java    From android-nfc with MIT License 6 votes vote down vote up
/**
 * 创建NDEF文本数据
 *
 * @param text
 * @return
 */
public static NdefRecord createTextRecord(String text) {
    byte[] langBytes = Locale.CHINA.getLanguage().getBytes(Charset.forName("US-ASCII"));
    Charset utfEncoding = Charset.forName("UTF-8");
    //将文本转换为UTF-8格式
    byte[] textBytes = text.getBytes(utfEncoding);
    //设置状态字节编码最高位数为0
    int utfBit = 0;
    //定义状态字节
    char status = (char) (utfBit + langBytes.length);
    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    //设置第一个状态字节,先将状态码转换成字节
    data[0] = (byte) status;
    //设置语言编码,使用数组拷贝方法,从0开始拷贝到data中,拷贝到data的1到langBytes.length的位置
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    //设置文本字节,使用数组拷贝方法,从0开始拷贝到data中,拷贝到data的1 + langBytes.length
    //到textBytes.length的位置
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    //通过字节传入NdefRecord对象
    //NdefRecord.RTD_TEXT:传入类型 读写
    NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
            NdefRecord.RTD_TEXT, new byte[0], data);
    return ndefRecord;
}
 
Example #7
Source File: BlogViewer.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void processIntent(Intent intent) {
  // Listing 18-18: Extracting NFC tag payloads
  String action = intent.getAction();

  if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
    Parcelable[] messages = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    if (messages != null) {
      for (Parcelable eachMessage : messages) {
        NdefMessage message = (NdefMessage) eachMessage;
        NdefRecord[] records = message.getRecords();

        if (records != null) {
          for (NdefRecord record : records) {
            String payload = new String(record.getPayload());
            Log.d(TAG, payload);
          }
        }
      }
    }
  }
}
 
Example #8
Source File: NfcReadUtilityImpl.java    From android-nfc-lib with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public SparseArray<String> readFromTagWithSparseArray(Intent nfcDataIntent) {
    Parcelable[] messages = nfcDataIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    SparseArray<String> resultMap = messages != null ? new SparseArray<String>(messages.length) : new SparseArray<String>();

    if (messages == null) {
        return resultMap;
    }

    for (Parcelable message : messages) {
        for (NdefRecord record : ((NdefMessage) message).getRecords()) {
            byte type = retrieveTypeByte(record.getPayload());

            String i = resultMap.get(type);
            if (i == null) {
                resultMap.put(type, parseAccordingToType(record));
            }
        }
    }

    return resultMap;
}
 
Example #9
Source File: NfcUtils.java    From WiFiKeyShare with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parse an NDEF message and return the corresponding Wi-Fi configuration
 *
 * Source: http://androidxref.com/6.0.1_r10/xref/packages/apps/Nfc/src/com/android/nfc/NfcWifiProtectedSetup.java
 *
 * @param message the NDEF message to parse
 * @return a WifiConfiguration extracted from the NDEF message
 */
private static WifiConfiguration parse(NdefMessage message) {
    NdefRecord[] records = message.getRecords();
    for (NdefRecord record : records) {
        if (new String(record.getType()).equals(NFC_TOKEN_MIME_TYPE)) {
            ByteBuffer payload = ByteBuffer.wrap(record.getPayload());
            while (payload.hasRemaining()) {
                short fieldId = payload.getShort();
                short fieldSize = payload.getShort();
                if (fieldId == CREDENTIAL_FIELD_ID) {
                    return parseCredential(payload, fieldSize);
                } else {
                    payload.position(payload.position() + fieldSize);
                }
            }
        }
    }
    return null;
}
 
Example #10
Source File: BeamActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_beam);

  // Listing 18-24: Extracting the Android Beam payload
  Parcelable[] messages
    = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
  if (messages != null) {
    NdefMessage message = (NdefMessage) messages[0];
    if (message != null) {
      NdefRecord record = message.getRecords()[0];
      String payload = new String(record.getPayload());
      Log.d(TAG, "Payload: " + payload);
    }
  }
}
 
Example #11
Source File: MainActivity.java    From APKMirror with GNU General Public License v2.0 6 votes vote down vote up
private void setupNFC(String url) {

        if (nfcAdapter != null) { // in case there is no NFC

            try {
                // create an NDEF message containing the current URL:
                NdefRecord rec = NdefRecord.createUri(url); // url: current URL (String or Uri)
                NdefMessage ndef = new NdefMessage(rec);
                // make it available via Android Beam:
                nfcAdapter.setNdefPushMessage(ndef, this, this);

            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }
 
Example #12
Source File: UnknownRecord.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
public static Record parse(NdefRecord ndefRecord) {
	
	/**
	The value 0x05 (Unknown) SHOULD be used to indicate that the type of the payload is
	unknown. This is similar to the "application/octet-stream" media type defined by MIME [RFC
	2046]. When used, the TYPE_LENGTH field MUST be zero and thus the TYPE field is omitted
	from the NDEF record. Regarding implementation, it is RECOMMENDED that an NDEF parser
	receiving an NDEF record of this type, without further context to its use, provides a mechanism
	for storing but not processing the payload (see section 4.2).

	 */
	
	// check that type is zero length
	byte[] type = ndefRecord.getType();
	if(type != null && type.length > 0) {
		throw new IllegalArgumentException("Record type not expected");
	}
	
	return new UnknownRecord(ndefRecord.getPayload());
}
 
Example #13
Source File: NfcTypeConverter.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Converts android.nfc.NdefMessage to mojo NfcMessage
 */
public static NfcMessage toNfcMessage(NdefMessage ndefMessage)
        throws UnsupportedEncodingException {
    NdefRecord[] ndefRecords = ndefMessage.getRecords();
    NfcMessage nfcMessage = new NfcMessage();
    List<NfcRecord> nfcRecords = new ArrayList<NfcRecord>();

    for (int i = 0; i < ndefRecords.length; i++) {
        if ((ndefRecords[i].getTnf() == NdefRecord.TNF_EXTERNAL_TYPE)
                && (Arrays.equals(ndefRecords[i].getType(), WEBNFC_URN.getBytes("UTF-8")))) {
            nfcMessage.url = new String(ndefRecords[i].getPayload(), "UTF-8");
            continue;
        }

        NfcRecord nfcRecord = toNfcRecord(ndefRecords[i]);
        if (nfcRecord != null) nfcRecords.add(nfcRecord);
    }

    nfcMessage.data = new NfcRecord[nfcRecords.size()];
    nfcRecords.toArray(nfcMessage.data);
    return nfcMessage;
}
 
Example #14
Source File: NfcTypeConverter.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Converts mojo NfcMessage to android.nfc.NdefMessage
 */
public static NdefMessage toNdefMessage(NfcMessage message) throws InvalidNfcMessageException {
    try {
        List<NdefRecord> records = new ArrayList<NdefRecord>();
        for (int i = 0; i < message.data.length; ++i) {
            records.add(toNdefRecord(message.data[i]));
        }
        records.add(NdefRecord.createExternal(DOMAIN, TYPE, message.url.getBytes("UTF-8")));
        NdefRecord[] ndefRecords = new NdefRecord[records.size()];
        records.toArray(ndefRecords);
        return new NdefMessage(ndefRecords);
    } catch (UnsupportedEncodingException | InvalidNfcMessageException
            | IllegalArgumentException e) {
        throw new InvalidNfcMessageException();
    }
}
 
Example #15
Source File: GcActionRecord.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
@Override
public NdefRecord getNdefRecord() {
	byte[] payload = null;

	if (hasAction() && hasActionRecord()) {
		throw new IllegalArgumentException("Expected action or action record, not both.");
	} 

	if (hasAction()) {
		payload = new byte[2];
		payload[0] = GcActionRecord.NUMERIC_CODE;
		payload[1] = (byte)action.getValue();
	}
	else if (hasActionRecord()) {
		byte[] subPayload = actionRecord.toByteArray();
	
		payload = new byte[subPayload.length + 1];
		payload[0] = 0;
		System.arraycopy(subPayload, 0, payload, 1, subPayload.length);
	} else {
		throw new IllegalArgumentException("Expected action or action record.");
	}
	
	return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, type, id != null ? id : EMPTY, payload);
}
 
Example #16
Source File: UriRecord.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
@Deprecated
protected static android.nfc.NdefRecord createUri(Uri uri) {
       if (uri == null) throw new NullPointerException("Uri is null");

       uri = normalizeScheme(uri);
       String uriString = uri.toString();
       if (uriString.length() == 0) throw new IllegalArgumentException("Uri is empty");

       byte prefix = 0;
       for (int i = 1; i < URI_PREFIX_MAP.length; i++) {
           if (uriString.startsWith(URI_PREFIX_MAP[i])) {
               prefix = (byte) i;
               uriString = uriString.substring(URI_PREFIX_MAP[i].length());
               break;
           }
       }
       byte[] uriBytes = uriString.getBytes(Charset.forName("UTF-8"));
       byte[] recordBytes = new byte[uriBytes.length + 1];
       recordBytes[0] = prefix;
       System.arraycopy(uriBytes, 0, recordBytes, 1, uriBytes.length);
       
	return new android.nfc.NdefRecord(TNF_WELL_KNOWN, RTD_URI, new byte[]{}, recordBytes);
   }
 
Example #17
Source File: ForegroundNdefPush.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
public static NdefRecord newTextRecord(String text, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = text.getBytes(utfEncoding);

    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);

    byte[] data = new byte[1 + langBytes.length + textBytes.length]; 
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);

    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}
 
Example #18
Source File: MainActivity.java    From QuickLyric with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(14)
private Lyrics getBeamedLyrics(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    if (rawMsgs != null && rawMsgs.length > 0) {
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        NdefRecord[] records = msg.getRecords();
        if (records.length > 0) {
            try {
                return Lyrics.fromBytes(records[0].getPayload());
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
 
Example #19
Source File: NFCWriteFragment.java    From android-nfc-tag-read-write with MIT License 6 votes vote down vote up
private void writeToNfc(Ndef ndef, String message){

        mTvMessage.setText(getString(R.string.message_write_progress));
        if (ndef != null) {

            try {
                ndef.connect();
                NdefRecord mimeRecord = NdefRecord.createMime("text/plain", message.getBytes(Charset.forName("US-ASCII")));
                ndef.writeNdefMessage(new NdefMessage(mimeRecord));
                ndef.close();
                //Write Successful
                mTvMessage.setText(getString(R.string.message_write_success));

            } catch (IOException | FormatException e) {
                e.printStackTrace();
                mTvMessage.setText(getString(R.string.message_write_error));

            } finally {
                mProgress.setVisibility(View.GONE);
            }

        }
    }
 
Example #20
Source File: SplashscreenActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void onCreate(final Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_splashscreen);

	// Jump to SensorsActivity after DELAY milliseconds 
	new Handler().postDelayed(() -> {
		final Intent newIntent = new Intent(SplashscreenActivity.this, FeaturesActivity.class);
		newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

		// Handle NFC message, if app was opened using NFC AAR record
		final Intent intent = getIntent();
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
			final Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
			if (rawMsgs != null) {
				for (Parcelable rawMsg : rawMsgs) {
					final NdefMessage msg = (NdefMessage) rawMsg;
					final NdefRecord[] records = msg.getRecords();

					for (NdefRecord record : records) {
						if (record.getTnf() == NdefRecord.TNF_MIME_MEDIA) {
							switch (record.toMimeType()) {
								case FeaturesActivity.EXTRA_APP:
									newIntent.putExtra(FeaturesActivity.EXTRA_APP, new String(record.getPayload()));
									break;
								case FeaturesActivity.EXTRA_ADDRESS:
									newIntent.putExtra(FeaturesActivity.EXTRA_ADDRESS, invertEndianness(record.getPayload()));
									break;
							}
						}
					}
				}
			}
		}
		startActivity(newIntent);
		finish();
	}, DELAY);
}
 
Example #21
Source File: HandoverRequestRecord.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
@Override
public NdefRecord getNdefRecord() {

	if (!hasCollisionResolution()) {
		throw new IllegalArgumentException("Expected collision resolution");
	}

	// implementation note: write alternative carriers and and collision resolution together
	if (!hasAlternativeCarriers()) {
		// At least a single alternative carrier MUST be specified by the Handover Requester.
		throw new IllegalArgumentException("Expected at least one alternative carrier");
	}
	List<NdefRecord> records = new ArrayList<NdefRecord>();

	// a collision resolution record
	records.add(collisionResolution.getNdefRecord());

	// n alternative carrier records
	for(Record record: alternativeCarriers) {
		records.add(record.getNdefRecord());
	}

	byte[] subPayload = new NdefMessage(records.toArray(new NdefRecord[records.size()])).toByteArray();
	byte[] payload = new byte[subPayload.length + 1];

	// major version, minor version
	payload[0] = (byte)((majorVersion << 4) | minorVersion);
	System.arraycopy(subPayload, 0, payload, 1, subPayload.length);
	
	return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_HANDOVER_REQUEST, id != null ? id : EMPTY, payload);
}
 
Example #22
Source File: NfcTypeConverter.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs well known type (TEXT or URI) NfcRecord
 */
private static NfcRecord createWellKnownRecord(NdefRecord record) {
    if (Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
        return createURLRecord(record.toUri());
    }

    if (Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
        return createTextRecord(record.getPayload());
    }

    return null;
}
 
Example #23
Source File: NFCTagReadWriteManager.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
private void readTagFromIntent(Intent intent) {
    if (intent != null){
        String action = intent.getAction();

        /*if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            uidRead = true;

            String uid = ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
            onTagReadListener.onUidRead(uid);
        }*/
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            tagRead = true;

            // get NDEF tag details
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                Ndef ndefTag = Ndef.get(tag);
                //int tagSize = ndefTag.getMaxSize();         // tag size
                tagIsWritable = ndefTag.isWritable();   // is tag writable?
                //String tagType = ndefTag.getType();            // tag type

                Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                if (rawMessages != null) {
                    NdefRecord[] records = ((NdefMessage) rawMessages[0]).getRecords();
                    String text = ndefRecordToString(records[0]);
                    onTagReadListener.onTagRead(text);
                }
            }
        }
    }
}
 
Example #24
Source File: GenericControlRecord.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
public static GenericControlRecord parseNdefRecord(NdefRecord ndefRecord) throws FormatException {
	byte[] payload = ndefRecord.getPayload();

	normalizeMessageBeginEnd(payload, 1, payload.length -1);
	
	Message payloadNdefMessage = Message.parseNdefMessage(payload, 1, payload.length - 1);

	GenericControlRecord genericControlRecord = new GenericControlRecord();
	genericControlRecord.setConfigurationByte(payload[0]);
	
	for (Record record : payloadNdefMessage) {
		if (record instanceof GcTargetRecord) {
			genericControlRecord.setTarget((GcTargetRecord)record);
		} else if (record instanceof GcActionRecord) {
			genericControlRecord.setAction((GcActionRecord)record);
		} else if (record instanceof GcDataRecord) {
			genericControlRecord.setData((GcDataRecord)record);
		} else {
			throw new IllegalArgumentException("Unexpected record " + record.getClass().getName());
		}
	}

	if (!genericControlRecord.hasTarget()) {
		throw new IllegalArgumentException("Expected target record");
	}
	
	return genericControlRecord;
}
 
Example #25
Source File: BaseActivity.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    if (shareUrl != null) {
        return new NdefMessage(new NdefRecord[]{
                NdefRecord.createUri(shareUrl)
        });
    }
    return null;
}
 
Example #26
Source File: CardboardDeviceParams.java    From Cardboard with Apache License 2.0 5 votes vote down vote up
public static CardboardDeviceParams createFromNfcContents(
		NdefMessage tagContents) {
	if (tagContents == null) {
		Log.w("CardboardDeviceParams",
				"Could not get contents from NFC tag.");
		return null;
	}
	CardboardDeviceParams deviceParams = new CardboardDeviceParams();
	for (NdefRecord record : tagContents.getRecords()) {
		if (deviceParams.parseNfcUri(record)) {
			break;
		}
	}
	return deviceParams;
}
 
Example #27
Source File: NdefRecordUtil.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private static NdefRecord createWellKnownTypeRecord(String type, String payload) {
    if (type.equals("text")) {
        return createTextRecord(payload);
    } else {
        throw new IllegalArgumentException();
    }
}
 
Example #28
Source File: NfcHelper.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
public static boolean setPushMessage(Activity activity, Uri toShare) {
    NfcAdapter adapter = getAdapter(activity);
    if (adapter != null) {
        adapter.setNdefPushMessage(new NdefMessage(new NdefRecord[]{
                NdefRecord.createUri(toShare),
        }), activity);
        return true;
    }
    return false;
}
 
Example #29
Source File: TextRecord.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
public static TextRecord parseNdefRecord(NdefRecord ndefRecord) {
	byte[] payload = ndefRecord.getPayload();

	int status = payload[0] & 0xff;
	int languageCodeLength = (status & TextRecord.LANGUAGE_CODE_MASK);
	String languageCode = new String(payload, 1, languageCodeLength);

	Charset textEncoding = ((status & TEXT_ENCODING_MASK) != 0) ? TextRecord.UTF16 : TextRecord.UTF8;

	return new TextRecord(new String(payload, 1 + languageCodeLength, payload.length - languageCodeLength - 1, textEncoding), textEncoding, new Locale(languageCode));
}
 
Example #30
Source File: NFCHandler.java    From timelapse-sony with GNU General Public License v3.0 5 votes vote down vote up
private static Pair<String, String> decodeSonyPPMMessage(NdefRecord ndefRecord) {

        if (!SONY_MIME_TYPE.equals(new String(ndefRecord.getType()))) {
            return null;
        }

        try {
            byte[] payload = ndefRecord.getPayload();

            int ssidBytesStart = 8;
            int ssidLength = payload[ssidBytesStart];

            byte[] ssidBytes = new byte[ssidLength];
            int ssidPointer = 0;
            for (int i = ssidBytesStart + 1; i <= ssidBytesStart + ssidLength; i++) {
                ssidBytes[ssidPointer++] = payload[i];
            }
            String ssid = new String(ssidBytes);

            int passwordBytesStart = ssidBytesStart + ssidLength + 4;
            int passwordLength = payload[passwordBytesStart];

            byte[] passwordBytes = new byte[passwordLength];
            int passwordPointer = 0;
            for (int i = passwordBytesStart + 1; i <= passwordBytesStart + passwordLength; i++) {
                passwordBytes[passwordPointer++] = payload[i];
            }
            String password = new String(passwordBytes);

            return new Pair<>(ssid, password);

        } catch (Exception e) {
            return null;
        }
    }