List of usage examples for android.nfc NdefRecord createApplicationRecord
public static NdefRecord createApplicationRecord(String packageName)
From source file:org.sufficientlysecure.keychain.ui.ViewKeyActivity.java
/** * NFC: Initialize NFC sharing if OS and device supports it *///w w w. ja va 2s. co m @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void initNfc(final Uri dataUri) { // check if NFC Beam is supported (>= Android 4.1) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // Implementation for the CreateNdefMessageCallback interface mNdefCallback = new NfcAdapter.CreateNdefMessageCallback() { @Override public NdefMessage createNdefMessage(NfcEvent event) { /* * 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. */ NdefMessage msg = new NdefMessage(NdefRecord.createMime(Constants.NFC_MIME, mNfcKeyringBytes), NdefRecord.createApplicationRecord(Constants.PACKAGE_NAME)); return msg; } }; // Implementation for the OnNdefPushCompleteCallback interface mNdefCompleteCallback = new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // A handler is needed to send messages to the activity when this // callback occurs, because it happens from a binder thread mNfcHandler.obtainMessage(NFC_SENT).sendToTarget(); } }; // Check for available NFC Adapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter != null) { /* * Retrieve mNfcKeyringBytes here asynchronously (to not block the UI) * and init nfc adapter afterwards. * mNfcKeyringBytes can not be retrieved in createNdefMessage, because this process * has no permissions to query the Uri. */ AsyncTask<Void, Void, Void> initTask = new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... unused) { try { Uri blobUri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri); mNfcKeyringBytes = (byte[]) mProviderHelper.getGenericData(blobUri, KeychainContract.KeyRingData.KEY_RING_DATA, ProviderHelper.FIELD_TYPE_BLOB); } catch (ProviderHelper.NotFoundException e) { Log.e(Constants.TAG, "key not found!", e); } // no AsyncTask return (Void) return null; } protected void onPostExecute(Void unused) { // Register callback to set NDEF message mNfcAdapter.setNdefPushMessageCallback(mNdefCallback, ViewKeyActivity.this); // Register callback to listen for message-sent success mNfcAdapter.setOnNdefPushCompleteCallback(mNdefCompleteCallback, ViewKeyActivity.this); } }; initTask.execute(); } } }
From source file:com.piusvelte.taplock.client.core.TapLockSettings.java
@Override protected void onResume() { super.onResume(); Intent intent = getIntent();//from w ww . j a v a2s . c o m if (mInWriteMode) { if (intent != null) { String action = intent.getAction(); if (mInWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) && intent.hasExtra(EXTRA_DEVICE_NAME)) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String name = intent.getStringExtra(EXTRA_DEVICE_NAME); if ((tag != null) && (name != null)) { // write the device and address String lang = "en"; // don't write the passphrase! byte[] textBytes = name.getBytes(); byte[] langBytes = null; int langLength = 0; try { langBytes = lang.getBytes("US-ASCII"); langLength = langBytes.length; } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } int textLength = textBytes.length; byte[] payload = new byte[1 + langLength + textLength]; // set status byte (see NDEF spec for actual bits) payload[0] = (byte) langLength; // copy langbytes and textbytes into payload if (langBytes != null) { System.arraycopy(langBytes, 0, payload, 1, langLength); } System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength); NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload); NdefMessage message = new NdefMessage( new NdefRecord[] { record, NdefRecord.createApplicationRecord(getPackageName()) }); // Get an instance of Ndef for the tag. Ndef ndef = Ndef.get(tag); if (ndef != null) { try { ndef.connect(); if (ndef.isWritable()) { ndef.writeNdefMessage(message); } ndef.close(); Toast.makeText(this, "tag written", Toast.LENGTH_LONG).show(); } catch (IOException e) { Log.e(TAG, e.toString()); } catch (FormatException e) { Log.e(TAG, e.toString()); } } else { NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); format.close(); Toast.makeText(getApplicationContext(), "tag written", Toast.LENGTH_LONG); } catch (IOException e) { Log.e(TAG, e.toString()); } catch (FormatException e) { Log.e(TAG, e.toString()); } } } mNfcAdapter.disableForegroundDispatch(this); } } } mInWriteMode = false; } else { SharedPreferences sp = getSharedPreferences(KEY_PREFS, MODE_PRIVATE); onSharedPreferenceChanged(sp, KEY_DEVICES); // check if configuring a widget if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { final String[] displayNames = TapLock.getDeviceNames(mDevices); final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) { mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle("Select device for widget") .setItems(displayNames, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // set the successful widget result Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); setResult(RESULT_OK, resultValue); // broadcast the new widget to update JSONObject deviceJObj = mDevices.get(which); dialog.cancel(); TapLockSettings.this.finish(); try { sendBroadcast(TapLock .getPackageIntent(TapLockSettings.this, TapLockWidget.class) .setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE) .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) .putExtra(EXTRA_DEVICE_NAME, deviceJObj.getString(KEY_NAME))); } catch (JSONException e) { Log.e(TAG, e.toString()); } } }).create(); mDialog.show(); } } } // start the service before binding so that the service stays around for faster future connections startService(TapLock.getPackageIntent(this, TapLockService.class)); bindService(TapLock.getPackageIntent(this, TapLockService.class), this, BIND_AUTO_CREATE); int serverVersion = sp.getInt(KEY_SERVER_VERSION, 0); if (mShowTapLockSettingsInfo && (mDevices.size() == 0)) { if (serverVersion < SERVER_VERSION) sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit(); mShowTapLockSettingsInfo = false; Intent i = TapLock.getPackageIntent(this, TapLockInfo.class); i.putExtra(EXTRA_INFO, getString(R.string.info_taplocksettings)); startActivity(i); } else if (serverVersion < SERVER_VERSION) { // TapLockServer has been updated sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit(); mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_hasupdate) .setMessage(R.string.msg_hasupdate) .setNeutralButton(R.string.button_getserver, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); mDialog = new AlertDialog.Builder(TapLockSettings.this) .setTitle(R.string.msg_pickinstaller) .setItems(R.array.installer_entries, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); final String installer_file = getResources() .getStringArray(R.array.installer_values)[which]; mDialog = new AlertDialog.Builder(TapLockSettings.this) .setTitle(R.string.msg_pickdownloader) .setItems(R.array.download_entries, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); String action = getResources() .getStringArray( R.array.download_values)[which]; if (ACTION_DOWNLOAD_SDCARD.equals(action) && copyFileToSDCard(installer_file)) Toast.makeText(TapLockSettings.this, "Done!", Toast.LENGTH_SHORT) .show(); else if (ACTION_DOWNLOAD_EMAIL .equals(action) && copyFileToSDCard( installer_file)) { Intent emailIntent = new Intent( android.content.Intent.ACTION_SEND); emailIntent.setType( "application/java-archive"); emailIntent.putExtra(Intent.EXTRA_TEXT, getString( R.string.email_instructions)); emailIntent.putExtra( Intent.EXTRA_SUBJECT, getString(R.string.app_name)); emailIntent.putExtra( Intent.EXTRA_STREAM, Uri.parse("file://" + Environment .getExternalStorageDirectory() .getPath() + "/" + installer_file)); startActivity(Intent.createChooser( emailIntent, getString( R.string.button_getserver))); } } }) .create(); mDialog.show(); } }).create(); mDialog.show(); } }).create(); mDialog.show(); } } }
From source file:net.networksaremadeofstring.rhybudd.WriteNFCActivity.java
public void WriteTag(final Tag receivedTag) { tagHandler.sendEmptyMessage(TAG_IO_IN_PROGRESS); (new Thread() { public void run() { //This could go all kinds of weird Ndef thisNdef = null;// w w w . j av a 2s.com try { thisNdef = Ndef.get(receivedTag); } catch (Exception e) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e); e.printStackTrace(); } if (null == thisNdef) { NdefFormatable formatter = null; try { formatter = NdefFormatable.get(receivedTag); formatter.connect(); formatter.format( new NdefMessage(new NdefRecord[] { NdefRecord.createApplicationRecord("io.d0") })); formatter.close(); thisNdef = Ndef.get(receivedTag); } catch (Exception d) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", d); d.printStackTrace(); tagHandler.sendEmptyMessage(FORMATEXCEPTION); } } try { if (null == thisNdef) { throw new FormatException("No NDEF Tag returned from get"); } else { thisNdef.connect(); } if (thisNdef.isWritable()) { //Is this a 203 or larger? if (thisNdef.getMaxSize() < aaRecord.toByteArray().length + idRecord.toByteArray().length) { /*Log.i("WriteTag","This tag was too big. tried to write " + (aaRecord.toByteArray().length + idRecord.toByteArray().length) + " to " + thisNdef.getMaxSize()); idRecord = NdefRecord.createMime("text/plain", Integer.toString(tagMetaData.getInt("i")).getBytes(Charset.forName("US-ASCII"))); Log.i("WriteTag Size Check", "Writing " + (idRecord.toByteArray().length + aaRecord.toByteArray().length) + " to " + thisNdef.getMaxSize());*/ tagHandler.sendEmptyMessage(SIZE_ERROR); } else { //Log.i("WriteTag Size Check", "Writing " + (aaRecord.toByteArray().length + idRecord.toByteArray().length) + " to " + thisNdef.getMaxSize()); NdefMessage tagMsg = new NdefMessage(new NdefRecord[] { idRecord, aaRecord }); //Log.i("WriteTag Size Check", "Wrote " + tagMsg.getByteArrayLength()); thisNdef.writeNdefMessage(tagMsg); thisNdef.makeReadOnly(); thisNdef.close(); tagHandler.sendEmptyMessage(WRITE_SUCCESS); } } else { tagHandler.sendEmptyMessage(READONLY); } } catch (IOException e) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e); tagHandler.sendEmptyMessage(IOEXCEPTION); } catch (FormatException e) { BugSenseHandler.sendExceptionMessage("WriteNFCActivity", "WriteTag", e); e.printStackTrace(); tagHandler.sendEmptyMessage(FORMATEXCEPTION); } } }).start(); }
From source file:com.evandroid.musica.fragment.LyricsViewFragment.java
@TargetApi(16) private void beamLyrics(final Lyrics lyrics, Activity activity) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter != null && nfcAdapter.isEnabled()) { if (lyrics.getText() != null) { nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() { @Override/*from w w w. ja v a 2 s. com*/ public NdefMessage createNdefMessage(NfcEvent event) { try { byte[] payload = lyrics.toBytes(); // whatever data you want to send NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "application/lyrics".getBytes(), new byte[0], payload); return new NdefMessage(new NdefRecord[] { record, // your data NdefRecord.createApplicationRecord("com.geecko.QuickLyric"), // the "application record" }); } catch (IOException e) { return null; } } }, activity); } } }
From source file:ch.bfh.instacircle.NetworkActiveActivity.java
@Override public void onNewIntent(Intent intent) { if (writeNfcEnabled) { // Handle the NFC part... SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0); String text = preferences.getString("SSID", "N/A") + "||" + preferences.getString("password", "N/A"); // create a new NdefRecord NdefRecord record = createMimeRecord("application/ch.bfh.instacircle", text.getBytes()); // create a new Android Application Record NdefRecord aar = NdefRecord.createApplicationRecord(getPackageName()); // create a ndef message NdefMessage message = new NdefMessage(new NdefRecord[] { record, aar }); // extract tag from the intent Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); // write the tag writeTag(tag, message);/*from w w w . j a va2 s . c o m*/ // close the dialog writeNfcEnabled = false; writeNfcTagDialog.dismiss(); } }
From source file:com.example.multi_ndef.Frag_Write.java
/** * Format a tag and write our NDEF message *//*from w w w. ja va 2 s. c o m*/ //@SuppressLint("NewApi") private boolean writeTag(Tag tag) { // record to launch Play Store if app is not installed NdefRecord appRecord = NdefRecord.createApplicationRecord("com.example.multi_ndef"); try { ENGLISH = Locale.ENGLISH; encodeInUtf8 = true; } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "Locale Error " + e.toString(), Toast.LENGTH_SHORT); toast.show(); } try { textRecord = createTextRecord(getText(), ENGLISH, encodeInUtf8); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "Text Conversion error " + e.toString(), Toast.LENGTH_SHORT); toast.show(); } try { uriRecord = NdefRecord.createUri(getUri()); } catch (Exception e) { Toast toast = Toast.makeText(getApplicationContext(), "Uri Conversion error " + e.toString(), Toast.LENGTH_SHORT); toast.show(); } byte[] mimeBytes = MimeType.AppName.getBytes(Charset.forName("US-ASCII")); byte[] mimeBytesBT = MimeType.AppNameBT.getBytes(Charset.forName("US-ASCII")); byte[] v_data = VCard(); // Here data is written byte[] payload = data(); // payload in hex //Comments by neha - 3 Jul 2014 byte[] payloadBT = btData(); NdefRecord VcardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/x-vcard".getBytes(), new byte[0], v_data); NdefRecord BTcardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytesBT, new byte[0], payloadBT); NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload); NdefRecord SMSRecord = NdefRecord.createUri(SMSpayload); NdefRecord MailRecord = NdefRecord.createUri(Mailpayload); NdefRecord TeleRecord = NdefRecord.createUri(Telepayload); NdefRecord LocationRecord = NdefRecord.createUri(Locationpayload); NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, textRecord, uriRecord, BTcardRecord, VcardRecord, SMSRecord, MailRecord, TeleRecord, LocationRecord, appRecord }); // ringProgressDialog.dismiss(); try { // see if tag is already NDEF formatted Ndef ndef = Ndef.get(tag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) { displayMessage("Read-only tag."); return false; } // work out how much space we need for the data int size = message.toByteArray().length; if (ndef.getMaxSize() < size) { displayMessage("Tag doesn't have enough free space."); return false; } ndef.writeNdefMessage(message); displayMessage("Multiple NDEF Records written to tag successfully."); return true; } else { // attempt to format tag NdefFormatable format = NdefFormatable.get(tag); if (format != null) { try { format.connect(); format.format(message); displayMessage("Tag written successfully!\nClose this app and scan tag."); return true; } catch (IOException e) { displayMessage("Unable to format tag to NDEF."); return false; } } else { displayMessage("Tag doesn't appear to support NDEF format."); return false; } } } catch (Exception e) { displayMessage("Failed to write tag"); } return false; }