Java 类android.nfc.NdefRecord 实例源码

项目:android-nfc    文件:ReadTextActivity.java   
/**
 * 读取NFC标签文本数据
 */
private void readNfcTag(Intent intent) {
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage msgs[] = null;
        int contentSize = 0;
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
                contentSize += msgs[i].toByteArray().length;
            }
        }
        try {
            if (msgs != null) {
                NdefRecord record = msgs[0].getRecords()[0];
                String textRecord = parseTextRecord(record);
                mTagText += textRecord + "\n\ntext\n" + contentSize + " bytes";
            }
        } catch (Exception e) {
        }
    }
}
项目:iosched-reader    文件:BeamUtils.java   
/**
 * 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 Activity#setIntent(android.content.Intent)}) to something
 * the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent).
 */
public static void tryUpdateIntentFromBeam(Activity activity) {
    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.makeContentItemType(
                ScheduleContract.Sessions.CONTENT_TYPE_ID).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);
        }
    }
}
项目:TapIn    文件:HubMain.java   
private String getTextFromNdefRecord(NdefRecord ndefRecord)
{
    String content = null;

    try
    {
        byte[] payload = ndefRecord.getPayload();
        String encoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTf-8";

        int languageSize = payload[0] & 0063;

        content = new String(payload, languageSize+1, payload.length - languageSize - 1, encoding);
    }
    catch (UnsupportedEncodingException e)
    {
        Log.e("createTextRecord", e.getMessage());
    }

    return content;
}
项目:TapIn    文件:add3.java   
private NdefRecord createTextRecord (String message)
{
    try
    {
        byte[] language;
        language = Locale.getDefault().getLanguage().getBytes("UTF-8");

        final byte[] text = message.getBytes("UTF-8");
        final int languageSize = language.length;
        final int textLength = text.length;

        final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);

        payload.write((byte) (languageSize & 0x1F));
        payload.write(language, 0, languageSize);
        payload.write(text, 0, textLength);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
    }
    catch (UnsupportedEncodingException e)
    {
        Log.e("createTextRecord", e.getMessage());
    }
    return null;
}
项目:android-nfc    文件:WriteTextActivity.java   
/**
 * 创建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;
}
项目:android-nfc    文件:WriteUriActivity.java   
public void onNewIntent(Intent intent) {
    Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{createUriRecord(mUri)});
    boolean result = writeTag(ndefMessage, detectedTag);
    if (result) {
        Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "写入失败", Toast.LENGTH_SHORT).show();
    }
}
项目:android-nfc    文件:WriteUriActivity.java   
/**
 * 将Uri转成NdefRecord
 *
 * @param uriStr
 * @return
 */
public static NdefRecord createUriRecord(String uriStr) {
    byte prefix = 0;
    for (Byte b : UriPrefix.URI_PREFIX_MAP.keySet()) {
        String prefixStr = UriPrefix.URI_PREFIX_MAP.get(b).toLowerCase();
        if ("".equals(prefixStr))
            continue;
        if (uriStr.toLowerCase().startsWith(prefixStr)) {
            prefix = b;
            uriStr = uriStr.substring(prefixStr.length());
            break;
        }
    }
    byte[] data = new byte[1 + uriStr.length()];
    data[0] = prefix;
    System.arraycopy(uriStr.getBytes(), 0, data, 1, uriStr.length());
    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], data);
    return record;
}
项目:buildAPKsSamples    文件:Beam.java   
/**
 * Implementation for the CreateNdefMessageCallback interface
 */
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    Time time = new Time();
    time.setToNow();
    String text = ("Beam me up!\n\n" +
            "Beam Time: " + time.format("%H:%M:%S"));
    NdefMessage msg = new NdefMessage(NdefRecord.createMime(
            "application/com.example.android.beam", text.getBytes())
     /**
      * The Android Application Record (AAR) is commented out. When a device
      * receives a push with an AAR in it, the application specified in the AAR
      * is guaranteed to run. The AAR overrides the tag dispatch system.
      * You can add it back in to guarantee that this
      * activity starts when receiving a beamed message. For now, this code
      * uses the tag dispatch system.
      */
      //,NdefRecord.createApplicationRecord("com.example.android.beam")
    );
    return msg;
}
项目:Quick-Tip-Consumer    文件:NFCReadActivity.java   
private String readNFCTag(Intent intent){
    String response=null;
    if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())){
        //从标签读取数据
        Parcelable[] nfcMsgs=intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES
        );
        NdefMessage msgs[]=null;
        int contentSize=0;
        if(nfcMsgs!=null){
            msgs=new NdefMessage[nfcMsgs.length];
            // 标签可能存储多个NdefMessage对象,一般情况下只有一个
            for(int i=0;i<nfcMsgs.length;i++){
                // 转换为NdefMessage对象
                msgs[i]= (NdefMessage) nfcMsgs[i];
                // 计算数据的总长度
                contentSize+=msgs[i].toByteArray().length;
            }
        }
        try{
            if(msgs!=null){
                // 只读第一个信息
                NdefRecord record=msgs[0].getRecords()[0];
                response=parseTextRecord(record);
                System.out.println(response);
            }
        }
        catch (Exception e){
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }
    return response;
}
项目:Quick-Tip-Consumer    文件:NFCReadActivity.java   
private String parseTextRecord(NdefRecord record){
    String response=null;
    // 验证TNF是否为TNF_WELL_KNOWN
    if(record.getTnf()!=NdefRecord.TNF_WELL_KNOWN) {
        System.out.println("不是TNF_WELL_KNOW");
        return null;
    }

    byte[] payload=record.getPayload();
    Byte statusByte=payload[0];
    String textCoding=((statusByte&0x80)==0)?"utf-8":"utf-16";
    int codeLength=statusByte&0x3f;
    try{
        response=new String(payload,codeLength+1,payload.length-codeLength-1,textCoding);
    }
    catch(UnsupportedEncodingException e){
        Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
    }
    return response;
}
项目:iosched-reader    文件:BeamUtils.java   
/**
 * Sets this activity's Android Beam message to one representing the given session.
 */
public static void setBeamSessionUri(Activity activity, Uri sessionUri) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter == null) {
        // No NFC :-(
        return;
    }

    nfcAdapter.setNdefPushMessage(new NdefMessage(
            new NdefRecord[]{
                    new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                            ScheduleContract.makeContentItemType(
                                    ScheduleContract.Sessions.CONTENT_TYPE_ID).getBytes(),
                            new byte[0],
                            sessionUri.toString().getBytes())
            }), activity);
}
项目:Movie-Notifier-Android    文件:WatcherBottomSheet.java   
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    cinemas = DBHelper.getInstance(getContext()).getCinemas();

    watcher = new Gson().fromJson(getArguments().getString("watcher"), Watcher.class);

    nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
    if(nfcAdapter != null) {
        nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
            @Override
            public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
                return new NdefMessage(
                        new NdefRecord[] {
                                NdefRecord.createUri(BuildConfig.SERVER_BASE_URL + "w/" + watcher.getID()),
                                NdefRecord.createApplicationRecord(BuildConfig.APPLICATION_ID)
                        }
                );
            }
        }, getActivity());
    }
}
项目:phonk    文件:PNfc.java   
/**
 * Write text to a tag
 *
 * @param textToWrite the text to write
 */
public void write(String textToWrite) {

    Locale locale = Locale.US;
    final byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("UTF-8"));
    final byte[] textBytes = textToWrite.getBytes(Charset.forName("UTF-8"));

    final int utfBit = 0;
    final char status = (char) (utfBit + langBytes.length);
    final 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);

    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
    NdefRecord[] records = {record};
    messageToWrite = new NdefMessage(records);
}
项目:PairingExample    文件:MainActivity.java   
private void readText(NdefRecord record) {
    int start;
    String payload = record.toString();
    String MAC;

    start = payload.indexOf("payload=");
    MAC = payload.substring(start + 12);

    MACs[mac_cnt] = MAC.substring(10, 12) + ":";
    MACs[mac_cnt] += MAC.substring(8, 10) + ":";
    MACs[mac_cnt] += MAC.substring(6, 8) + ":";
    MACs[mac_cnt] += MAC.substring(4, 6) + ":";
    MACs[mac_cnt] += MAC.substring(2, 4) + ":";
    MACs[mac_cnt] += MAC.substring(0, 2);

    mac_cnt++;

}
项目:TraiNFCUI    文件:Tap.java   
private NdefRecord createTextRecord(String content) {
    try {
        byte[] language;
        language = Locale.getDefault().getLanguage().getBytes("UTF-8");

        final byte[] text = content.getBytes("UTF-8");
        final int languageSize = language.length;
        final int textLength = text.length;
        final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);

        payload.write((byte) (languageSize & 0x1F));
        payload.write(language, 0, languageSize);
        payload.write(text, 0, textLength);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());

    } catch (UnsupportedEncodingException e) {
        Log.e("createTextRecord", e.getMessage());
    }
    return null;
}
项目:AndroidthingsStudy    文件:ForegroundNdefPush.java   
@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    mAdapter = NfcAdapter.getDefaultAdapter(this);

    // Create an NDEF message a URL
    mMessage = new NdefMessage(NdefRecord.createUri("http://www.android.com"));

    setContentView(R.layout.foreground_dispatch);
    mText = (TextView) findViewById(R.id.text);

    if (mAdapter != null) {
        mAdapter.setNdefPushMessage(mMessage, this);
        mText.setText("Tap another Android phone with NFC to push a URL");
    } else {
        mText.setText("This phone is not NFC enabled.");
    }
}
项目:AndroidthingsStudy    文件:Beam.java   
/**
 * Implementation for the CreateNdefMessageCallback interface
 */
@Override
public NdefMessage createNdefMessage(NfcEvent event) {
    Time time = new Time();
    time.setToNow();
    String text = ("Beam me up!\n\n" +
            "Beam Time: " + time.format("%H:%M:%S"));
    NdefMessage msg = new NdefMessage(NdefRecord.createMime(
            "application/com.example.android.beam", text.getBytes())
     /**
      * The Android Application Record (AAR) is commented out. When a device
      * receives a push with an AAR in it, the application specified in the AAR
      * is guaranteed to run. The AAR overrides the tag dispatch system.
      * You can add it back in to guarantee that this
      * activity starts when receiving a beamed message. For now, this code
      * uses the tag dispatch system.
      */
      //,NdefRecord.createApplicationRecord("com.example.android.beam")
    );
    return msg;
}
项目:WiFiKeyShare    文件:NfcUtils.java   
/**
 * 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;
}
项目:p2p-android-sdk    文件:PeerService.java   
public void registerNfcCallback(Activity activity) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter != null) {
        // Register callback
        nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
            @Override
            public NdefMessage createNdefMessage(NfcEvent event) {
                return new NdefMessage(
                    new NdefRecord[] {
                        NdefRecord.createMime(
                            "application/vnd.com.pgrenaud.android.p2p.beam",
                            getPeerRepository().encode().getBytes()
                        )
                    }
                );
            }
        }, activity);

        Log.d("PeerService", "NdefPushMessageCallback registered");
    }
}
项目:smconf-android    文件:BeamUtils.java   
/**
 * Sets this activity's Android Beam message to one representing the given session.
 */
public static void setBeamSessionUri(Activity activity, Uri sessionUri) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter == null) {
        // No NFC :-(
        return;
    }

    nfcAdapter.setNdefPushMessage(new NdefMessage(
            new NdefRecord[]{
                    new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                            ScheduleContract.makeContentItemType(
                                    ScheduleContract.Sessions.CONTENT_TYPE_ID).getBytes(),
                            new byte[0],
                            sessionUri.toString().getBytes())
            }), activity);
}
项目:smconf-android    文件:BeamUtils.java   
/**
 * 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 Activity#setIntent(android.content.Intent)}) to something
 * the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent).
 */
public static void tryUpdateIntentFromBeam(Activity activity) {
    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.makeContentItemType(
                ScheduleContract.Sessions.CONTENT_TYPE_ID).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);
        }
    }
}
项目:basscast    文件:Stream.java   
private static byte[] parseNdefRecord(final NdefRecord record) {
    if (record.getTnf() != NdefRecord.TNF_EXTERNAL_TYPE) {
        throw new IllegalArgumentException("Invalid TNF: " + record.getTnf());
    }
    final byte[] type = record.getType();
    if (type == null) {
        throw new NullPointerException("Type must not be null");
    }
    final String typeString = new String(type);
    if (!typeString.equalsIgnoreCase(BuildConfig.APPLICATION_ID + ":stream")) {
        throw new IllegalArgumentException("Invalid type: " + typeString);
    }

    final byte[] bytes = record.getPayload();
    if (bytes == null) {
        throw new NullPointerException("Payload must not be null");
    }
    return bytes;
}
项目:basscast    文件:EditStreamActivity.java   
private void parseNdefMessage(final Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
            NfcAdapter.EXTRA_NDEF_MESSAGES);
    Log.d(TAG, "#msgs: " + rawMsgs.length);
    for (Parcelable rawMsg : rawMsgs) {
        NdefMessage msg = (NdefMessage) rawMsg;
        Log.d(TAG, "#records: " + msg.getRecords().length);
        for (NdefRecord record : msg.getRecords()) {
            try {
                mStream = new Stream(record);
                return;
            } catch (Exception e) {
                Log.e(TAG, "NDEF record is not a stream", e);
            }
        }
    }
    throw new IllegalArgumentException("Invalid NDEF message");
}
项目:basscast    文件:StreamTest.java   
public void testStreamToNdefRecord() {
    final Stream s = new Stream();
    s.setId(5);
    s.setTitle("some stream");
    s.setUrl("http://example.com/stream");
    s.setMimeType("audio/mp3");

    NdefRecord record = s.toNdefRecord();
    final Stream newStream = new Stream(record);

    assertEquals(s.getTitle(), newStream.getTitle());
    assertEquals(s.getUrl(), newStream.getUrl());
    assertEquals(s.getMimeType(), newStream.getMimeType());

    assertEquals(record, newStream.toNdefRecord());
}
项目:TappyBLE    文件:TcmpMessageDescriptor.java   
private static String parseNdefFoundResponse(Context ctx, NdefFoundResponse resp) {
    NdefMessage msg = resp.getMessage();
    NdefRecord[] records = msg.getRecords();
    if(records.length == 0) {
        return ctx.getString(R.string.ndef_no_record);
    }
    else if (records.length == 1) {
        return String.format(ctx.getString(R.string.ndef_found_response_single_record),
                ByteUtils.bytesToHex(resp.getTagCode()),
                parseTagType(ctx, resp.getTagType()),
                parseNdefRecord(ctx, records[0]));
    }
    else {
        return String.format(ctx.getString(R.string.ndef_found_response_multi_record),
                ByteUtils.bytesToHex(resp.getTagCode()),
                parseTagType(ctx, resp.getTagType()),
                parseNdefRecord(ctx, records[0]));
    }
}
项目:TappyBLE    文件:TcmpMessageDescriptor.java   
private static String parseNdefRecord(Context ctx, NdefRecord record) {
    if(record.getTnf() == NdefRecord.TNF_WELL_KNOWN) {
        if(Arrays.equals(record.getType(),NdefRecord.RTD_URI)) {
            return parseWellKnownUriRecord(ctx,record);
        }
        else if (Arrays.equals(record.getType(),NdefRecord.RTD_TEXT)) {
            return parseWellKnownTextRecord(ctx, record);
        }
        else {
            return parseGenericNdefRecord(ctx,record);
        }
    }
    else {
        return parseGenericNdefRecord(ctx,record);
    }
}
项目:TappyBLE    文件:TcmpMessageDescriptor.java   
private static String parseTnf(Context ctx, NdefRecord record) {
    short tnf = record.getTnf();
    switch(tnf) {
        case NdefRecord.TNF_ABSOLUTE_URI:
            return ctx.getString(R.string.tnf_abs_uri);
        case NdefRecord.TNF_EMPTY:
            return ctx.getString(R.string.tnf_empty);
        case NdefRecord.TNF_EXTERNAL_TYPE:
            return ctx.getString(R.string.tnf_external);
        case NdefRecord.TNF_MIME_MEDIA:
            return ctx.getString(R.string.tnf_mime_media);
        case NdefRecord.TNF_UNCHANGED:
            return ctx.getString(R.string.tnf_unchanged);
        case NdefRecord.TNF_WELL_KNOWN:
            return ctx.getString(R.string.tnf_well_known);
        default:
            return ctx.getString(R.string.tnf_unknown);
    }
}
项目:TappyBLE    文件:TcmpMessageDescriptor.java   
private static String parseType(Context ctx, NdefRecord record) {
    byte[] type = record.getType();
    if(Arrays.equals(type, NdefRecord.RTD_URI))
        return ctx.getString(R.string.rtd_uri);
    else if(Arrays.equals(type,NdefRecord.RTD_ALTERNATIVE_CARRIER))
        return ctx.getString(R.string.rtd_alt_carrier);
    else if(Arrays.equals(type,NdefRecord.RTD_HANDOVER_CARRIER))
        return ctx.getString(R.string.rtd_handover_carrier);
    else if(Arrays.equals(type,NdefRecord.RTD_HANDOVER_REQUEST))
        return ctx.getString(R.string.rtd_handover_request);
    else if(Arrays.equals(type,NdefRecord.RTD_HANDOVER_SELECT))
        return ctx.getString(R.string.rtd_handover_select);
    else if(Arrays.equals(type,NdefRecord.RTD_SMART_POSTER))
        return ctx.getString(R.string.rtd_smart_poster);
    else if(Arrays.equals(type,NdefRecord.RTD_TEXT))
        return ctx.getString(R.string.rtd_text);
    else if (record.getTnf() == NdefRecord.TNF_MIME_MEDIA)
        return new String(type);
    else
        return ByteUtils.bytesToHex(type);
}
项目:APKMirror    文件:MainActivity.java   
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();
            }
        }
    }
项目:Eulen    文件:nfctagbase.java   
protected void writeTAG(Tag tag) throws IOException, FormatException {
    Ndef ndefTag = Ndef.get(tag);
    byte[] stringBytes = passphrase.getBytes();

    NdefRecord data = NdefRecord.createMime(CONST.NFC_MIME_LOGIN, stringBytes);
    NdefMessage message = new NdefMessage(data);

    if (ndefTag != null) { //write to formatted tag
        ndefTag.connect();
        ndefTag.writeNdefMessage(message);
    } else { //format the tag
        NdefFormatable format = NdefFormatable.get(tag);
        if(format != null) {
            format.connect();
            format.format(message);
        }
    }
}
项目:2015-Google-I-O-app    文件:BeamUtils.java   
/**
 * Sets this activity's Android Beam message to one representing the given session.
 */
public static void setBeamSessionUri(Activity activity, Uri sessionUri) {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter == null) {
        // No NFC :-(
        return;
    }

    nfcAdapter.setNdefPushMessage(new NdefMessage(
            new NdefRecord[]{
                    new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                            ScheduleContract.makeContentItemType(
                                    ScheduleContract.Sessions.CONTENT_TYPE_ID).getBytes(),
                            new byte[0],
                            sessionUri.toString().getBytes())
            }), activity);
}
项目:2015-Google-I-O-app    文件:BeamUtils.java   
/**
 * 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 Activity#setIntent(android.content.Intent)}) to something
 * the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent).
 */
public static void tryUpdateIntentFromBeam(Activity activity) {
    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.makeContentItemType(
                ScheduleContract.Sessions.CONTENT_TYPE_ID).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);
        }
    }
}
项目:py-eventos-android    文件:NfcSenderUtils.java   
public static boolean setAppDataPushMessageCallbackIfAvailable(Activity activity, final CreateNfcAppDataCallback callback) {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
    if (adapter == null) {
        return false;
    }
    final String packageName = activity.getPackageName();
    adapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            byte[] appData = callback.createNfcAppData();
            if (appData == null) {
                return null;
            }
            NdefRecord[] records = new NdefRecord[] { createMimeRecord("application/" + packageName, appData),
                    NdefRecord.createApplicationRecord(packageName) };
            return new NdefMessage(records);
        }

    }, activity);
    return true;
}
项目:RxBluetoothAuto    文件:Home.java   
public String nfcRead(Tag t)
{
    Tag tag = t;
    Ndef ndef = Ndef.get(tag);
    if (ndef == null) {
        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) {}
        }
    }

    return null;

}
项目:android-nfc-wrapper    文件:NFCReadTask.java   
@Override
protected NFCTag doInBackground(Intent... params) {
    Intent intent = params[0];

    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    Ndef ndef = Ndef.get(tag);

    if (ndef == null) {
        return null;
    }

    NdefMessage ndefMessage = ndef.getCachedNdefMessage();

    if(ndefMessage != null) {
        NdefRecord[] records = ndefMessage.getRecords();
        for (NdefRecord ndefRecord : records) {
            try {
                return new NFCTag(ndefRecord).decode();
            } catch (UnsupportedEncodingException e) {
                Log.e("NFC", "Unsupported Encoding", e);
            }
        }
    }

    return null;
}
项目:android-nfc-tag-read-write    文件:NFCWriteFragment.java   
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);
            }

        }
    }
项目:archive-carro-inteligente    文件:NFCHandler.java   
public NdefMessage getNdefMessageFromText(String messageText)
{
    try
    {
        // Get UTF-8 byte
        byte[] lang = Locale.getDefault().getLanguage().getBytes("UTF-8");
        byte[] text = messageText.getBytes("UTF-8"); // Content in UTF-8

        int langSize = lang.length;
        int textLength = text.length;

        ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + langSize + textLength);
        payload.write((byte) (langSize & 0x1F));
        payload.write(lang, 0, langSize);
        payload.write(text, 0, textLength);
        NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());
        return new NdefMessage(new NdefRecord[]{record});
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:archive-carro-inteligente    文件:NFCHandler.java   
public String getTagText() throws Exception
{
    if (tag == null)
    {
        throw new Exception("Please call handle new read as tag is null");
    }
    Ndef ndef = Ndef.get(tag);
    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)
            {
                Toast.makeText(activity, "Unsupported encoding", Toast.LENGTH_SHORT).show();
            }
        }
    }
    return null;
}
项目:archive-carro-inteligente    文件:NFCHandler.java   
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);
}
项目:ots15-companion    文件:NfcSenderUtils.java   
public static boolean setAppDataPushMessageCallbackIfAvailable(Activity activity, final CreateNfcAppDataCallback callback) {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
    if (adapter == null) {
        return false;
    }
    final String packageName = activity.getPackageName();
    adapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {

        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            byte[] appData = callback.createNfcAppData();
            if (appData == null) {
                return null;
            }
            NdefRecord[] records = new NdefRecord[]{createMimeRecord("application/" + packageName, appData),
                    NdefRecord.createApplicationRecord(packageName)};
            return new NdefMessage(records);
        }

    }, activity);
    return true;
}