コード例 #1
0
  private void readTag(Tag t) {
    // get NDEF tag details
    Ndef ndefTag = Ndef.get(t);

    // get NDEF message details
    NdefMessage ndefMesg = ndefTag.getCachedNdefMessage();
    if (ndefMesg == null) {
      return;
    }
    NdefRecord[] ndefRecords = ndefMesg.getRecords();
    if (ndefRecords == null) {
      return;
    }
    for (NdefRecord record : ndefRecords) {
      short tnf = record.getTnf();
      String type = new String(record.getType());
      if (tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(type.getBytes(), NdefRecord.RTD_URI)) {
        String url = new String(record.getPayload());
        if (url.startsWith(ATTENDEE_URL_PREFIX)) {
          Intent i = new Intent(Intent.ACTION_VIEW);
          i.setData(Uri.parse("https://" + url.substring(1)));
          startActivity(i);
          return;
        }
      }
    }
  }
コード例 #2
0
ファイル: NfcActivity.java プロジェクト: vtloc/glass-earth
    @Override
    protected String doInBackground(Tag... params) {
      Tag tag = params[0];

      Ndef ndef = Ndef.get(tag);
      if (ndef == null) {
        // NDEF is not supported by this Tag.
        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) {
            Log.e(TAG, "Unsupported Encoding", e);
          }
        }
      }

      return null;
    }
コード例 #3
0
ファイル: TULReader.java プロジェクト: MegaDevs/Nostradamus
 public static NdefRecord[] readRecords(Tag tag)
     throws IOException, FormatException, NotReadableException {
   Ndef ndefTag = Ndef.get(tag);
   if (ndefTag == null) {
     throw new NotReadableException("The tag doesn't support Ndef tech");
   }
   ndefTag.connect();
   NdefMessage message = ndefTag.getNdefMessage();
   NdefRecord[] records = message.getRecords();
   ndefTag.close();
   return records;
 }
コード例 #4
0
  private void write(String text, Tag tag) throws IOException, FormatException {

    NdefRecord[] records = {createWellKnownRecord(text)};
    NdefMessage message = new NdefMessage(records);
    // Get an instance of Ndef for the tag.
    Ndef ndef = Ndef.get(tag);
    // Enable I/O
    ndef.connect();
    // Write the message
    ndef.writeNdefMessage(message);
    // Close the connection
    ndef.close();
  }
コード例 #5
0
ファイル: TagWriteActivity.java プロジェクト: pboos/Emera
  boolean writeTag(NdefMessage message, NdefMessage messageWithoutPhoto, Tag tag) {
    try {
      Ndef ndef = Ndef.get(tag);
      if (ndef != null) {
        return writeToTag(message, messageWithoutPhoto, ndef);
      } else {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
          if (formatAndWrite(format, message) || formatAndWrite(format, messageWithoutPhoto)) {
            return true;
          } else {
            toast(getString(R.string.write_tag_failed_format));
            return false;
          }
        } else {
          toast(getString(R.string.write_tag_failed_ndef));
          return false;
        }
      }
    } catch (Exception e) {
      toast(getString(R.string.write_tag_failed));
    }

    return false;
  }
コード例 #6
0
ファイル: TULReader.java プロジェクト: MegaDevs/Nostradamus
 public static String[] readStrings(Tag tag)
     throws IOException, FormatException, NotReadableException {
   Ndef ndefTag = Ndef.get(tag);
   if (ndefTag == null) {
     throw new NotReadableException("The tag doesn't support Ndef tech");
   }
   ndefTag.connect();
   NdefMessage message = ndefTag.getNdefMessage();
   NdefRecord[] records = message.getRecords();
   String[] out = new String[records.length];
   int i = 0;
   for (NdefRecord rec : records) {
     out[i++] = new String(rec.getPayload(), Charset.forName("UTF-8"));
   }
   ndefTag.close();
   return out;
 }
コード例 #7
0
 private void connectToNDEF(Tag tag) {
   Ndef ndef = Ndef.get(tag);
   try {
     receiveTab.append("\n" + ndef.getType());
     NdefMessage message = ndef.getCachedNdefMessage();
     if (message != null) {
       NdefRecord[] recordsFromMessage = message.getRecords();
       for (int i = 0; i < recordsFromMessage.length; i++) {
         printMessage(recordsFromMessage[i]);
       }
     } else {
       receiveTab.append("\nNull message");
     }
     receiveTab.append("\nNDEF did work!");
   } catch (Exception ex) {
     receiveTab.append("\nNDEF did not work");
   }
 }
コード例 #8
0
 // El método write es el más importante, será el que se encargue de crear el mensaje
 // y escribirlo en nuestro tag.
 private void write(String text, Tag tag) throws IOException, FormatException {
   try {
     // Creamos un array de elementos NdefRecord. Este Objeto representa un registro del mensaje
     // NDEF
     // Para crear el objeto NdefRecord usamos el método createRecord(String s)
     NdefRecord[] records = {createRecord(text)};
     // NdefMessage encapsula un mensaje Ndef(NFC Data Exchange Format). Estos mensajes están
     // compuestos por varios registros encapsulados por la clase NdefRecord
     NdefMessage message = new NdefMessage(records);
     // Obtenemos una instancia de Ndef del Tag
     Ndef ndef = Ndef.get(tag);
     ndef.connect();
     ndef.writeNdefMessage(message);
     ndef.close();
   } catch (Exception e) {
     Log.d("WRITE", "Excepción: " + e.getMessage());
   }
 } // write
コード例 #9
0
ファイル: NFCActivity.java プロジェクト: ssdd1886/NFCUtil
 private boolean writeTxtToTag(String textToWrite, Tag tag) throws IOException, FormatException {
   if (tag == null) {
     Log.d(TAG, "writeTxtToTag: tag is null!");
     Toast.makeText(this, "Tag is null", Toast.LENGTH_SHORT).show();
     return false;
   }
   NdefRecord record = createRecord(textToWrite);
   if (record == null) {
     Log.d(TAG, "writeTxtToTag: record is null!");
     return false;
   } else {
     NdefRecord[] records = {record};
     NdefMessage message = new NdefMessage(records);
     Ndef ndef = Ndef.get(tag);
     ndef.connect();
     ndef.writeNdefMessage(message);
     ndef.close();
   }
   return true;
 }
コード例 #10
0
 public void writeTag(NdefMessage ndefMessage, Tag tag) {
   try {
     Ndef ndef = Ndef.get(tag);
     if (ndef != null) {
       ndef.connect();
       ndef.writeNdefMessage(ndefMessage);
     } else {
       NdefFormatable format = NdefFormatable.get(tag);
       if (format != null) {
         try {
           format.connect();
           format.format(ndefMessage);
         } catch (IOException e) {
           Log.e(Constants.LOGTAG, e.getMessage(), e);
         }
       }
     }
   } catch (Exception e) {
     Log.e(Constants.LOGTAG, e.getMessage(), e);
   }
 }
コード例 #11
0
ファイル: TagWriteActivity.java プロジェクト: pboos/Emera
  private boolean writeToTag(NdefMessage message, NdefMessage messageWithoutPhoto, Ndef ndef)
      throws IOException, FormatException {
    int size = message.toByteArray().length;
    int sizeSmall = messageWithoutPhoto.toByteArray().length;

    ndef.connect();

    if (!ndef.isWritable()) {
      toast("Tag is read-only.");
      return false;
    }

    NdefMessage messageToWrite = message;

    if (ndef.getMaxSize() < size) {
      if (ndef.getMaxSize() < sizeSmall) {
        toast(getResources().getString(R.string.write_tag_failed_size, ndef.getMaxSize(), size));
        return false;
      } else {
        messageToWrite = messageWithoutPhoto;
      }
    }

    ndef.writeNdefMessage(messageToWrite);
    return true;
  }
コード例 #12
0
  @Override
  protected void onNewIntent(Intent intent) {
    // if extra is present, it has priority on the saved poll
    Poll serializedPoll = (Poll) intent.getSerializableExtra("poll");
    if (serializedPoll != null) {
      poll = serializedPoll;
    }

    if (intent.getParcelableExtra(NfcAdapter.EXTRA_TAG) != null) {
      Intent broadcastIntent = new Intent(BroadcastIntentTypes.nfcTagTapped);
      broadcastIntent.putExtra(
          NfcAdapter.EXTRA_TAG, intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
      LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
    }

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

    if (ndef == null) {
      Toast.makeText(
              this, getResources().getText(R.string.toast_nfc_tag_read_failed), Toast.LENGTH_LONG)
          .show();
    } else {
      NdefMessage msg;
      msg = ndef.getCachedNdefMessage();
      config = new String(msg.getRecords()[0].getPayload()).split("\\|\\|");

      // saving the values that we got
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString("SSID", ssid);
      editor.commit();

      if (checkIdentification()) {
        connect(config, this);
      }
    }

    super.onNewIntent(intent);
  }
コード例 #13
0
 public boolean writeNdefMessageToTag(NdefMessage message, Tag detectedTag) {
   int size = message.toByteArray().length;
   try {
     Ndef ndef = Ndef.get(detectedTag);
     if (ndef != null) {
       ndef.connect();
       if (!ndef.isWritable()) {
         Toast.makeText(this, "Tag is read-only.", Toast.LENGTH_SHORT).show();
         return false;
       }
       if (ndef.getMaxSize() < size) {
         Toast.makeText(
                 this,
                 "The data cannot written to tag,Tag capacity is "
                     + ndef.getMaxSize()
                     + " bytes, message is "
                     + size
                     + " bytes.",
                 Toast.LENGTH_SHORT)
             .show();
         return false;
       }
       ndef.writeNdefMessage(message);
       ndef.close();
       Toast.makeText(this, "Message is written tag.", Toast.LENGTH_SHORT).show();
       return true;
     } else {
       NdefFormatable ndefFormat = NdefFormatable.get(detectedTag);
       if (ndefFormat != null) {
         try {
           ndefFormat.connect();
           ndefFormat.format(message);
           ndefFormat.close();
           Toast.makeText(this, "The data is written to the tag ", Toast.LENGTH_SHORT).show();
           return true;
         } catch (IOException e) {
           Toast.makeText(this, "Failed to format tag", Toast.LENGTH_SHORT).show();
           return false;
         }
       } else {
         Toast.makeText(this, "NDEF is not supported", Toast.LENGTH_SHORT).show();
         return false;
       }
     }
   } catch (Exception e) {
     Toast.makeText(this, "Write opreation is failed", Toast.LENGTH_SHORT).show();
   }
   return false;
 }
コード例 #14
0
 public void writeTag(NdefMessage message, Tag tag) {
   int size = message.toByteArray().length;
   String mess;
   try {
     Ndef ndef = Ndef.get(tag);
     if (ndef != null) {
       ndef.connect();
       if (!ndef.isWritable()) {
         this.status = 0;
         this.message = "Tag is read-only";
       }
       if (ndef.getMaxSize() < size) {
         mess = "Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.";
         this.status = 0;
         this.message = mess;
       }
       ndef.writeNdefMessage(message);
       if (writeProtect) ndef.makeReadOnly();
       mess = "Wrote message to pre-formatted tag.";
       this.status = 1;
       this.message = mess;
     } else {
       NdefFormatable format = NdefFormatable.get(tag);
       if (format != null) {
         try {
           format.connect();
           format.format(message);
           mess = "Formatted tag and wrote message";
           this.status = 1;
           this.message = mess;
         } catch (IOException e) {
           mess = "Failed to format tag.";
           this.status = 0;
           this.message = mess;
         }
       } else {
         mess = "Tag doesn't support NDEF.";
         this.status = 0;
         this.message = mess;
       }
     }
   } catch (Exception e) {
     mess = "Failed to write tag";
     this.status = 0;
     this.message = mess;
   }
 }
コード例 #15
0
ファイル: NfcWriter.java プロジェクト: nexelem/boxplorer
    /** Metoda zapisujaca w tle wiadomosc do tagu NFC Przed sprawdzeniem formatuje tag */
    @Override
    protected Void doInBackground(Void... nop) {
      int size = this.msg.toByteArray().length;
      try {
        Ndef ndef = Ndef.get(this.tag);
        if (ndef == null) {
          NdefFormatable formatable = NdefFormatable.get(this.tag);

          if (formatable != null) {
            try {
              formatable.connect();
              try {
                formatable.format(this.msg);
              } catch (Exception e) {
                this.returnText = R.string.nfc_tag_refused_to_format;
              }
            } catch (Exception e) {
              this.returnText = R.string.nfc_tag_refused_to_connect;
            } finally {
              formatable.close();
            }
          } else {
            this.returnText = R.string.nfc_tag_does_not_support_ndef;
          }
        } else {
          ndef.connect();

          try {
            if (!ndef.isWritable()) {
              this.returnText = R.string.nfc_tag_is_read_only;
            } else if (ndef.getMaxSize() < size) {
              this.returnText = R.string.nfc_message_is_too_big;
            } else {
              ndef.writeNdefMessage(this.msg);
              this.returnText = R.string.nfc_tag_saved;
              this.returnStatus = Activity.RESULT_OK;
            }
          } catch (Exception e) {
            this.returnText = R.string.nfc_tag_refused_to_connect;
          } finally {
            ndef.close();
          }
        }
      } catch (Exception e) {
        Log.e(TAG, "Exception when writing tag", e);
        this.returnText = R.string.nfc_general_exception;
      }

      return (null);
    }
コード例 #16
0
  /**
   * タグ書き込みを行う
   *
   * @param message
   * @param tag
   * @return
   */
  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()) {
          toast("Tag is read-only.");
          return false;
        }
        if (ndef.getMaxSize() < size) {
          toast("Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.");
          return false;
        }

        ndef.writeNdefMessage(message);
        mVib.vibrate(300);
        toast("Wrote message to pre-formatted tag.");
        return true;
      } else {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
          try {
            format.connect();
            format.format(message);
            mVib.vibrate(300);
            toast("Formatted tag and wrote message");
            return true;
          } catch (IOException e) {
            toast("Failed to format tag.");
            return false;
          }
        } else {
          toast("Tag doesn't support NDEF.");
          return false;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      toast("Failed to write tag");
    }
    return false;
  }
コード例 #17
0
 public boolean writableTag(Tag tag, Context context) {
   try {
     Ndef ndef = Ndef.get(tag);
     if (ndef != null) {
       ndef.connect();
       if (!ndef.isWritable()) {
         Toast.makeText(context, "Tag is read-only.", Toast.LENGTH_SHORT).show();
         ndef.close();
         return false;
       }
       ndef.close();
       return true;
     }
   } catch (Exception e) {
     Toast.makeText(context, "Failed to read tag", Toast.LENGTH_SHORT).show();
   }
   return false;
 }
コード例 #18
0
  /** Actually writes data into tag (sticker). */
  private void writeTag(NdefMessage message, Tag tag) {
    int size = message.toByteArray().length;

    try {
      Ndef ndef = Ndef.get(tag);
      if (ndef != null) {
        ndef.connect();

        if (!ndef.isWritable()) {
          toast(R.string.tag_read_only);
          return;
        }
        if (ndef.getMaxSize() < size) {
          toast(R.string.exceeded_tag_capacity);
          return;
        }

        ndef.writeNdefMessage(message);
        toast(R.string.sticker_write_success);
      } else {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
          try {
            format.connect();
            format.format(message);
            toast(R.string.sticker_write_success);
          } catch (IOException e) {
            toast(R.string.sticker_write_error);
          }
        } else {
          toast(R.string.sticker_write_error);
        }
      }
    } catch (FormatException e) {
      toast(R.string.sticker_write_error);
    } catch (IOException e) {
      toast(R.string.sticker_write_error);
    }
  }
コード例 #19
0
ファイル: MainActivity.java プロジェクト: aml2610/autolec
  @Override
  protected void onResume() {

    // initialising
    super.onResume();
    textView.setText("LOADING...");

    // Checks whether the app was started by:
    //  - reading a tag  (which means we should communicate with the database and change phone
    // settings)
    //  - the user (which means the welcome info and settings activity should start)
    Intent intent = this.getIntent();
    if (intent.getAction().contains("NDEF")) {

      // raw message from tag
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

      if (rawMsgs != null) {

        // The tag
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        // its records
        NdefRecord[] records = Ndef.get(tag).getCachedNdefMessage().getRecords();

        // the info on it in byte shape
        byte[] payload = records[0].getPayload();

        // Get the Text Encoding
        String textEncoding;
        if ((payload[0] & 128) == 0) textEncoding = "UTF-8";
        else textEncoding = "UTF-16";

        // Get the Language Code
        int languageCodeLength = payload[0] & 0063;

        try {
          // the configured message on the tag (the id of the room in which it is put)
          String roomID =
              new String(
                  payload,
                  languageCodeLength + 1,
                  payload.length - languageCodeLength - 1,
                  textEncoding);

          // the class which communicates with the sql database
          DatabaseConnecter sql = new DatabaseConnecter(MainActivity.this);

          // the id of the module which is currently on schedule
          int moduleID = sql.getModule(Integer.parseInt(roomID));
          if (moduleID == 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("There is no lecture at this time in this room!").setTitle("Alert!");
            builder.setPositiveButton(
                "Ok",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int id) {
                    // User clicked OK button
                    MainActivity.this.finish();
                  }
                });
            AlertDialog dialog = builder.create();
            dialog.show();
          }

          // a welcome message on screen
          textView.setText(
              "The current lecture is "
                  + sql.getModuleName(moduleID)
                  + "! Your lecturer is "
                  + sql.getLecturerName(moduleID));

          // tells the server that the student scanned the tag (went in the lecture or went out)
          sql.setPurpose(studentID);

          // gets the link for the lecture notes and enables the button to browse them

          if (sql.getPurpose(studentID).equals("out")) {
            lecnoteButton.setVisibility(Button.INVISIBLE);
            lecnoteButton.setEnabled(false);
            surveyButton.setVisibility(Button.VISIBLE);
            surveyButton.setEnabled(true);
          } else {
            lecnoteButton.setVisibility(Button.VISIBLE);
            lecnoteButton.setEnabled(true);
            surveyButton.setVisibility(Button.INVISIBLE);
            surveyButton.setEnabled(false);
          }

          link = sql.getLecnotes(moduleID);
          if (link.equals("None")) lecnoteButton.setText("No lecture notes available!");
          else lecnoteButton.setEnabled(true);

          surveyLink = sql.getSurvey(moduleID);
          if (surveyLink.equals("None")) surveyButton.setText("No lecture notes available!");
          else surveyButton.setEnabled(true);
        }

        // should not happen if the tag is configured properly
        catch (UnsupportedEncodingException e) {
          System.out.println("invalid tag " + e.toString());
        } catch (NumberFormatException e) {
          System.out.println("invalid tag " + e.toString());
        }
      }

    } // end of if
    else {
      // starts the settings activity
      Intent configIntent = new Intent(MainActivity.this, ConfigActivity.class);
      startActivity(configIntent);
    }
  }
コード例 #20
0
  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()) {
          Toast.makeText(
                  this, "Cannot write to this tag. This tag is read-only.", Toast.LENGTH_LONG)
              .show();
          return false;
        }
        if (ndef.getMaxSize() < size) {
          Toast.makeText(
                  this,
                  "Cannot write to this tag. Message size ("
                      + size
                      + " bytes) exceeds this tag's capacity of "
                      + ndef.getMaxSize()
                      + " bytes.",
                  Toast.LENGTH_LONG)
              .show();
          return false;
        }

        ndef.writeNdefMessage(message);
        Toast.makeText(this, "A pre-formatted tag was successfully updated.", Toast.LENGTH_LONG)
            .show();
        return true;
      } else {
        NdefFormatable format = NdefFormatable.get(tag);
        if (format != null) {
          try {
            format.connect();
            format.format(message);
            Toast.makeText(
                    this, "This tag was successfully formatted and updated.", Toast.LENGTH_LONG)
                .show();
            return true;
          } catch (IOException e) {
            Toast.makeText(
                    this, "Cannot write to this tag due to I/O Exception.", Toast.LENGTH_LONG)
                .show();
            return false;
          }
        } else {
          Toast.makeText(
                  this,
                  "Cannot write to this tag. This tag does not support NDEF.",
                  Toast.LENGTH_LONG)
              .show();
          return false;
        }
      }
    } catch (Exception e) {
      Toast.makeText(this, "Cannot write to this tag due to an Exception.", Toast.LENGTH_LONG)
          .show();
    }

    return false;
  }