Java 类android.nfc.NdefMessage 实例源码

项目:TapIn    文件:HubMain.java   
@Override
public void onNewIntent(Intent intent)
{
    super.onNewIntent(intent);

    if(intent.hasExtra(NfcAdapter.EXTRA_TAG ))
    {
        if(BackgroundTask.isNetworkAvailable(HubMain.this))
        {
            gifImageView.setVisibility(View.INVISIBLE);
            spinner.setVisibility(View.VISIBLE);
        }
        Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

        if(parcelables != null && parcelables.length > 0)
        {
            readTextfromMessage((NdefMessage)parcelables[0]);
        }
    }
}
项目: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);
        }
    }
}
项目:okwallet    文件:WalletActivity.java   
private void handleIntent(final Intent intent) {
    final String action = intent.getAction();

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        final String inputType = intent.getType();
        final NdefMessage ndefMessage = (NdefMessage) intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)[0];
        final byte[] input = Nfc.extractMimePayload(Constants.MIMETYPE_TRANSACTION, ndefMessage);

        new BinaryInputParser(inputType, input) {
            @Override
            protected void handlePaymentIntent(final PaymentIntent paymentIntent) {
                cannotClassify(inputType);
            }

            @Override
            protected void error(final int messageResId, final Object... messageArgs) {
                dialog(WalletActivity.this, null, 0, messageResId, messageArgs);
            }
        }.parse();
    }
}
项目:mobile-store    文件:RepoDetailsActivity.java   
private void processIntent(Intent i) {
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) {
        Parcelable[] rawMsgs =
                i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        String url = new String(msg.getRecords()[0].getPayload());
        Utils.debugLog(TAG, "Got this URL: " + url);
        Toast.makeText(this, "Got this URL: " + url, Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        intent.setClass(this, ManageReposActivity.class);
        startActivity(intent);
        finish();
    }
}
项目:TapIn    文件:add3.java   
private void formatTag(Tag tag, NdefMessage ndefMessage)
{
    try
    {
        NdefFormatable ndefFormatable = NdefFormatable.get(tag);

        if (ndefFormatable == null)
        {
            Toast.makeText(this, "Tag is not formatable", Toast.LENGTH_LONG).show();
        }

        ndefFormatable.connect();
        ndefFormatable.format(ndefMessage);
        ndefFormatable.close();
    }
    catch (Exception e)
    {
        Log.e("formatTag", e.getMessage());
    }
}
项目: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   
/**
 * 写入标签
 *
 * @param message
 * @param tag
 * @return
 */
public static boolean writeTag(NdefMessage message, Tag tag) {
    int size = message.toByteArray().length;
    try {
        Ndef ndef = Ndef.get(tag);
        if (ndef != null) {
            ndef.connect();
            if (!ndef.isWritable()) {
                return false;
            }
            if (ndef.getMaxSize() < size) {
                return false;
            }
            ndef.writeNdefMessage(message);
            return true;
        }
    } catch (Exception e) {
    }
    return false;
}
项目: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;
}
项目:buildAPKsSamples    文件:Beam.java   
/**
 * Parses the NDEF Message from the intent and prints to the TextView
 */
void processIntent(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
            NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    NdefMessage msg = (NdefMessage) rawMsgs[0];
    // record 0 contains the MIME type, record 1 is the AAR, if present
    mInfoText.setText(new String(msg.getRecords()[0].getPayload()));
}
项目: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;
}
项目: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);
}
项目:wNFCard    文件:NewCardActivity.java   
private void resolveIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs;
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        } else {
            // Unknown tag type
            //byte[] empty = new byte[0];
            //byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            showTagId(tag);
            //byte[] payload = dumpTagData(tag).getBytes();
            //NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
            //NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
            //msgs = new NdefMessage[] { msg };
        }
        // Setup the views
        //buildTagViews(msgs);
    }
}
项目:TraiNFCUI    文件:Tap.java   
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
        Toast.makeText(this, "NfcIntent!", Toast.LENGTH_SHORT).show();

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        NdefMessage ndefMessage = createNdefMessage("My string content!");

        writeNdefMessage(tag, ndefMessage);
    }
}
项目: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;
}
项目:AndroidthingsStudy    文件:Beam.java   
/**
 * Parses the NDEF Message from the intent and prints to the TextView
 */
void processIntent(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
            NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    NdefMessage msg = (NdefMessage) rawMsgs[0];
    // record 0 contains the MIME type, record 1 is the AAR, if present
    mInfoText.setText(new String(msg.getRecords()[0].getPayload()));
}
项目: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");
    }
}
项目:p2p-android-sdk    文件:PeerService.java   
/**
 * Merge all the known peers by an other peer sent over Android Beam (NFC).
 * You must call {@link PeerHive#sync()} and update your UI yourself after calling this method.
 *
 * @param intent Intent sent by Android Beam containing a NDEF payload.
 */
public void handleNfcIntent(@Nullable Intent intent) {
    if (intent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        try {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

            // only one message sent during the beam
            NdefMessage msg = (NdefMessage) rawMsgs[0];

            // record 0 contains the MIME type, record 1 is the AAR, if present
            String json = new String(msg.getRecords()[0].getPayload());

            getPeerRepository().mergeAll(PeerRepository.decode(json));
        } catch (JsonSyntaxException | IndexOutOfBoundsException e) {
            Log.e("PeerService", "handleNfcIntent", e);
        }
    }
}
项目: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    文件: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");
}
项目: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]));
    }
}
项目: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);
            }

        }
    }
项目:fdroid    文件:RepoDetailsActivity.java   
@TargetApi(9)
void processIntent(Intent i) {
    if (Build.VERSION.SDK_INT < 9) {
        return;
    }
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) {
        Parcelable[] rawMsgs =
                i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        String url = new String(msg.getRecords()[0].getPayload());
        Utils.debugLog(TAG, "Got this URL: " + url);
        Toast.makeText(this, "Got this URL: " + url, Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        intent.setClass(this, ManageReposActivity.class);
        startActivity(intent);
        finish();
    }
}
项目:AppHub    文件:RepoDetailsActivity.java   
@TargetApi(9)
void processIntent(Intent i) {
    if (Build.VERSION.SDK_INT < 9)
        return;
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) {
        Parcelable[] rawMsgs =
                i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        String url = new String(msg.getRecords()[0].getPayload());
        Utils.debugLog(TAG, "Got this URL: " + url);
        Toast.makeText(this, "Got this URL: " + url, Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        intent.setClass(this, ManageReposActivity.class);
        startActivity(intent);
        finish();
    }
}
项目: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 void writeTag(Tag tag, NdefMessage message)
{
    if (tag != null) {
        try {
            Ndef ndefTag = Ndef.get(tag);

            if (ndefTag == null) {
                // Let's try to format the Tag in NDEF
                NdefFormatable nForm = NdefFormatable.get(tag);
                if (nForm != null) {
                    nForm.connect();
                    nForm.format(message);
                    nForm.close();
                }
            }
            else {
                ndefTag.connect();
                ndefTag.writeNdefMessage(message);
                ndefTag.close();
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}
项目: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;
}
项目: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;
}