示例#1
0
 /** 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
   DebugUtil.d(TAG, new String(msg.getRecords()[0].getPayload()));
 }
示例#2
0
    @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
 private void processIntent(Intent intent) {
   Log.d("ANDROID_LAB", "processIntent...");
   Bitmap bitmap = null;
   Parcelable[] ndefMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
   if (ndefMsgs != null) {
     Log.d("ANDROID_LAB", "ndefMsgs.size=" + ndefMsgs.length);
     String str = "";
     for (int i = 0; i < ndefMsgs.length; i++) {
       NdefMessage msg = (NdefMessage) ndefMsgs[i];
       NdefRecord[] records = msg.getRecords();
       if (records != null) {
         Log.d("ANDROID_LAB", "records.size=" + records.length);
         for (int k = 0; k < records.length; k++) {
           NdefRecord record = records[k];
           byte[] data = record.getPayload();
           if (data != null) {
             if (k == 0) {
               str += new String(data);
             } else if (k == 1) {
               bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
             }
           }
         }
       }
     }
     txtPushContent.setText(str);
     if (bitmap != null) {
       txtPushContent.setCompoundDrawablesWithIntrinsicBounds(
           null, null, null, new BitmapDrawable(bitmap));
     }
   }
 }
  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;
        }
      }
    }
  }
示例#5
0
  // on recognition of nfc event
  @Override
  protected void onResume() {
    super.onResume();
    Intent intent = getIntent();
    // appendTotal();

    // initialize gesture detector, for swipe
    // gestureDetector = new GestureDetector(this, new SwipeGestureDetector());

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
      Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

      NdefMessage message = (NdefMessage) rawMessages[0]; // only one message transferred
      String amount = new String(message.getRecords()[0].getPayload());

      // showBalance.setText("125");
      // showBalance.setVisibility(View.INVISIBLE); //REMOVE FOR FRIENDSHIP

      appendTotal();
      // showBalance.setText("1225");

      /*Intent intentt = new Intent(this, OpenCamera.class);
      startActivity(intentt);*/
    }
  }
示例#6
0
  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;
  }
示例#7
0
  /**
   * Method to send the messages over another device
   *
   * @param NfcIntent - NFC intent to pass data
   */
  private void handleNfcIntent(Intent NfcIntent) {
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(NfcIntent.getAction())) {
      Parcelable[] receivedArray =
          NfcIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

      if (receivedArray != null) {
        messagesToReceiveQueue.clear();
        NdefMessage receivedMessage = (NdefMessage) receivedArray[0];
        NdefRecord[] linkRecords = receivedMessage.getRecords();

        for (NdefRecord record : linkRecords) {
          String message = new String(record.getPayload());
          if (!message.equals(getPackageName())) {
            messagesToReceiveQueue.add(message);
          }
        }

        Toast.makeText(
                this,
                "Total " + messagesToReceiveQueue.size() + "Messages received",
                Toast.LENGTH_LONG)
            .show();

        updateTextViews();
      } else {
        Toast.makeText(this, "Received Blank", Toast.LENGTH_LONG).show();
      }
    }
  }
  private void handleIntent(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());

      beamFragment.loadUrl(url);
    }
  }
示例#9
0
 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;
 }
示例#10
0
  /** 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
    String id = new String(msg.getRecords()[0].getPayload());

    String url =
        "https://www.facebook.com/dialog/friends/?id="
            + id
            + "&app_id=581136295234749&redirect_uri=http://www.facebook.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
  }
示例#11
0
 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;
 }
示例#12
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");
   }
 }
示例#13
0
 private void processIntent(Intent intent) {
   Parcelable[] ndefMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
   NdefMessage msg = (NdefMessage) ndefMessages[0];
   NdefRecord[] records = msg.getRecords();
   for (NdefRecord record : records) {
     String dataString = new String(record.getPayload());
     Scanner scanner = new Scanner(dataString);
     DataContainer dataContainer = new DataContainer();
     for (int i = 0; i < Constants.DATA_NAMES.length; i++) {
       if (Constants.DATA_FIELDS[i].equals("int")) {
         dataContainer.setData(Constants.DATA_NAMES[i], scanner.nextInt());
       } else {
         dataContainer.setData(Constants.DATA_NAMES[i], scanner.nextInt() == 1);
       }
     }
     mDBHelper.insertDataContainer(dataContainer);
   }
 }
示例#14
0
  /**
   * Configures the {@link mobisocial.nfc.Nfc} interface to set up a Bluetooth socket with another
   * device. The method both sets the foreground ndef messages and registers an {@link
   * mobisocial.nfc.NdefHandler} to look for incoming pairing requests.
   *
   * <p>When this method is called, a Bluetooth server socket is created, and the socket is closed
   * after a successful connection. You must call prepare() again to reinitiate the server socket.
   *
   * @return The server socket listening for peers.
   */
  public static BluetoothServerSocket prepare(
      Nfc nfc, OnConnectedListener conn, NdefRecord[] ndef) {
    BluetoothConnecting btConnecting = new BluetoothConnecting(conn);
    NdefMessage handoverRequest = btConnecting.getHandoverRequestMessage(nfc.getContext());
    NdefRecord[] combinedRecords =
        new NdefRecord[ndef.length + handoverRequest.getRecords().length];

    int i = 0;
    for (NdefRecord r : ndef) {
      combinedRecords[i++] = r;
    }
    for (NdefRecord r : handoverRequest.getRecords()) {
      combinedRecords[i++] = r;
    }

    NdefMessage outbound = new NdefMessage(combinedRecords);
    nfc.getConnectionHandoverManager().addConnectionHandover(btConnecting);
    nfc.share(outbound);
    return btConnecting.mAcceptThread.mmServerSocket;
  }
示例#15
0
 /**
  * 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 android.app.Activity#setIntent(android.content.Intent)}) to something the
  * app can recognize (i.e. a normal {@link android.content.Intent#ACTION_VIEW} intent).
  */
 @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
 public static void tryUpdateIntentFromBeam(Activity activity) {
   if (UIUtils.hasICS()) {
     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.Sessions.CONTENT_ITEM_TYPE.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);
       }
     }
   }
 }
示例#16
0
    @Override
    public void doConnectionHandover(NdefMessage handoverRequest, int handover, int record)
        throws IOException {

      byte[] remoteCollision = handoverRequest.getRecords()[handover + 1].getPayload();
      if (remoteCollision[0] == mCollisionResolution[0]
          && remoteCollision[1] == mCollisionResolution[1]) {
        return; // They'll have to try again.
      }
      boolean amServer =
          (remoteCollision[0] < mCollisionResolution[0]
              || (remoteCollision[0] == mCollisionResolution[0]
                  && remoteCollision[1] < mCollisionResolution[1]));

      if (mAlwaysClient) {
        amServer = false;
      }

      if (!mConnectionStarted) {
        synchronized (BluetoothConnecting.this) {
          if (!mConnectionStarted) {
            mConnectionStarted = true;
            mmBtConnected.beforeConnect(amServer);
          }
        }
      }
      if (!amServer) {
        // Not waiting for a connection:
        mAcceptThread.cancel();
        Uri uri = Uri.parse(new String(handoverRequest.getRecords()[record].getPayload()));
        UUID serviceUuid = UUID.fromString(uri.getPath().substring(1));
        int channel = -1;
        String channelStr = uri.getQueryParameter("channel");
        if (null != channelStr) {
          channel = Integer.parseInt(channelStr);
        }

        BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(uri.getAuthority());
        new ConnectThread(remoteDevice, serviceUuid, channel).start();
      }
    }
示例#17
0
  @Override
  public void onNewIntent(Intent intent) {
    // onResume gets called after this to handle the intent
    if (NFC_SETTING) {
      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 strSite = new String(msg.getRecords()[0].getPayload());
      if (strSite != null && !strSite.equals("")) {
        servIP = strSite.substring(strSite.indexOf("servIP") + 7, strSite.indexOf("\n"));
        editText3.setText(servIP);
        editText4.setText("8888");
        editText5.setText("8080");
      }
    }

    Log.d("onNewIntent", "onNewIntent");
    setIntent(intent);
    return;
  }
示例#18
0
  void processIntent(Intent intent) {

    // Parses the NDEF Message from the 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

    String receivedTxt = new String(msg.getRecords()[0].getPayload());
    String receivedTxtArray[] = receivedTxt.split("\\|");

    if (receivedTxtArray.length >= 2) {
      Intent prompt = new Intent(getApplicationContext(), NfcRequestActivity.class);

      prompt.putExtra(NfcRequestActivity.PARAM_NAME, receivedTxtArray[0]);
      prompt.putExtra(NfcRequestActivity.PARAM_TOKEN, receivedTxtArray[1]);

      getIntent().setAction(null);
      startActivityForResult(prompt, 2);
    }
  }
示例#19
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);
  }
示例#20
0
  private ScanableTag messageToScanable(NdefMessage message) {
    NdefRecord record = message.getRecords()[0];

    // XXX Ignoring the first byte because it contains a flag we are not
    // paying attention to yet
    byte[] rawData = new byte[record.getPayload().length - 1];
    System.arraycopy(record.getPayload(), 1, rawData, 0, rawData.length);

    String text = decodePayload(rawData);

    String mimeType = decodePayload(record.getType());

    return new TagParser().parse(mimeType, text);
  }
 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
 void processNfcIntent(Intent intent) {
   nfcIntent = intent;
   Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
   // only one message sent during the beam
   NdefMessage msg = (NdefMessage) rawMsgs[0];
   // get encoded data
   String res = new String(msg.getRecords()[0].getPayload());
   // show progr bar
   showGroup(-1);
   // handle it
   Log.d(TAG, "Decoded raw res: " + res);
   isLeader = false;
   chosenNType = NetInfo.WiFi;
   if (res != null) {
     peerNetData = PeerNetInfo.decode(res);
     if (peerNetData != null) {
       Log.d(TAG, "Decoded PeerNetInfo: " + peerNetData.toString());
       Log.d(TAG, "chosen Ntype : " + chosenNType);
       setupWifiConn(peerNetData);
     }
   }
 }
 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;
 }
示例#23
0
  private void readTextFromMessage(NdefMessage ndefMessage) {

    NdefRecord[] ndefRecords = ndefMessage.getRecords();

    if (ndefRecords != null && ndefRecords.length > 0) {

      NdefRecord ndefRecord = ndefRecords[0];

      String tagContent = getTextFromNdefRecord(ndefRecord);

      // txtTagContent.setText(tagContent);

    } else {
      Toast.makeText(this, "No NDEF records found!", Toast.LENGTH_SHORT).show();
    }
  }
示例#24
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;
   }
 }
  /**
   * タグ書き込みを行う
   *
   * @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;
  }
示例#26
0
 public DINdefMessage(NdefMessage ndefMessage) {
   ndefMessage = (NdefMessage) ndefMessage.getRecords()[0].getPayload();
   NdefMessage ndefMessage2 = ndefMessage[4];
   this.mMajorVersion = ndefMessage2 >> 4;
   this.mMinorVersion = (byte) (ndefMessage2 & 15);
   ndefMessage2 =
       (NdefMessage) new BigInteger(Arrays.copyOfRange((byte[]) ndefMessage, 7, 9)).intValue();
   this.mSsid =
       new String(Arrays.copyOfRange((byte[]) ndefMessage, 7 + 2, (int) (ndefMessage2 + 9)));
   reference var3_3 = ndefMessage2 + 9 + 2;
   ndefMessage2 =
       (NdefMessage)
           new BigInteger(
                   Arrays.copyOfRange((byte[]) ndefMessage, (int) var3_3, (int) (var3_3 + 2)))
               .intValue();
   this.mPasswd =
       new String(
           Arrays.copyOfRange(
               (byte[]) ndefMessage, (int) var3_3, (int) ((var3_3 += 2) + ndefMessage2)));
 }
  /** 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);
    }
  }
示例#28
0
  /**
   * Process and handle the NFC beam and parse the data
   *
   * @param intent
   */
  private void processNFC(Intent intent) {

    // receive the data from the intent and store in an array
    Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // The NdefMessage that was sent from the NFC is the first thing stored in the rawMessages array
    NdefMessage ndefMessage = (NdefMessage) rawMessages[0];

    // parse the data that is stored as bytes into a String
    // The ndefMessage has the array of records of the person's data, so we get
    // each data and store it into the appropriate variable
    personName = new String(ndefMessage.getRecords()[0].getPayload());
    business = new String(ndefMessage.getRecords()[1].getPayload());
    address = new String(ndefMessage.getRecords()[2].getPayload());
    cityStateZip = new String(ndefMessage.getRecords()[3].getPayload());
    number = new String(ndefMessage.getRecords()[4].getPayload());
    email = new String(ndefMessage.getRecords()[5].getPayload());
    website = new String(ndefMessage.getRecords()[6].getPayload());
    fullAddress = address + ", " + cityStateZip;

    // Add the name of the person in the dialog box to tell the receiver of the card from whom
    // they are receiving the contact from
    final TextView tv = (TextView) findViewById(R.id.contact_receive);
    tv.append(" " + personName);
  }
  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;
  }
示例#30
0
  @Override
  protected void onResume() {
    txtNFC = (TextView) findViewById(R.id.textView_nfc);
    super.onResume();
    Intent intent = getIntent();
    // Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    // Log.i("detected tag", detectedTag.toString());
    // if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
    // {processIntent(getIntent());}

    if (NfcAdapter.getDefaultAdapter(this) != null) {

      NfcAdapter.getDefaultAdapter(this)
          .enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
      // Check if the Activity was started from Beam
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

        NdefMessage message = (NdefMessage) rawMessages[0]; // only one message transferred
        // Toast.makeText(this, new String(message.getRecords()[0].getPayload()),
        // Toast.LENGTH_LONG).show();

        String temp = new String(message.getRecords()[0].getPayload());
        Log.i("Payload: ", temp);
        Log.i("UUID: ", friendUUID = temp.split(",")[0]);
        Log.i("Username: "******",")[1]);
        txtNFC.setText(temp.split(",")[1] + " has successfully been added as a friend.");

        // brandon
        addFriendTask =
            new AsyncTask<Void, Void, Void>() {
              @Override
              protected Void doInBackground(Void... params) {
                Message msg = addFriendHandle.obtainMessage();
                String message =
                    associateFriends(
                        getApplicationContext(), userName, friendUserName, UUID, friendUUID);
                // String message = logIn(getApplicationContext(), txtUsername.getText().toString(),
                // txtPassword.getText().toString());
                Log.e(TAG, message);
                msg.obj = message;
                addFriendHandle.sendMessage(msg);
                return null;
              }

              @Override
              protected void onPostExecute(Void result) {
                // brandon - Because AsyncTasks can only be used once
                addFriendTask = null;
              }
            };

        addFriendTask.execute(null, null, null);
        // friendListview.setVisibility(View.VISIBLE);

        friendList = new ArrayList<String>();
        //		       //brandon
        friendsListTask =
            new AsyncTask<Void, Void, Void>() {
              @Override
              protected Void doInBackground(Void... params) {
                Message msg = friendsListHandle.obtainMessage();
                String message = getFriends(getApplicationContext(), userName);
                // String message = logIn(getApplicationContext(), txtUsername.getText().toString(),
                // txtPassword.getText().toString());
                Log.e(TAG, message);
                msg.obj = message;
                friendsListHandle.sendMessage(msg);
                return null;
              }

              @Override
              protected void onPostExecute(Void result) {
                // brandon - Because AsyncTasks can only be used once
                friendsListTask = null;
              }
            };

        friendsListTask.execute(null, null, null);
        friendListview.setVisibility(View.VISIBLE);

        friendAdapter =
            new ExtendedArrayAdapter(
                getApplicationContext(), R.layout.simple_list_item_1, friendList);
        friendListview.setAdapter(friendAdapter);

        friendListview.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {

              @Override
              public void onItemClick(
                  AdapterView<?> parent, final View view, int position, long id) {}
            });
      } else
        // Toast.makeText(this, "Waiting for NDEF Message", Toast.LENGTH_LONG).show();
        txtNFC.setText("Waiting for NDEF Message");
    }
  }