@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]); } } }
/** * 读取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) { } } }
/** * 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); } } }
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(); } }
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(); } }
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()); } }
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(); } }
/** * 写入标签 * * @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; }
/** * 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; }
/** * 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())); }
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; }
/** * 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); }
@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()); } }
/** * 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); }
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); } }
@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); } }
@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."); } }
/** * 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; }
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"); } }
/** * 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); } } }
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"); }
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])); } }
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(); } } }
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); } } }
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; }
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; }
@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; }
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); } } }
@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(); } }
@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(); } }
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; }
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(); } } }
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; }
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; }