private void handleIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

      String type = intent.getType();
      if (MIME_TEXT_PLAIN.equals(type)) {

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        new NdefReaderTask().execute(tag);

      } else {
        Log.d(TAG, "Wrong mime type: " + type);
      }
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {

      // In case we would still use the Tech Discovered Intent
      Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      String[] techList = tag.getTechList();
      String searchedTech = Ndef.class.getName();

      for (String tech : techList) {
        if (searchedTech.equals(tech)) {
          new NdefReaderTask().execute(tag);
          break;
        }
      }
    }
  }
 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);
       Parcelable tag = intent.getParcelableExtra(NfcAdapter.EXTRA_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
     populateCardID(msgs);
   }
 }
 private void handleIntent(Intent intent) {
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())
       || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())
       || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
     Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
     if (rawMsgs != null) {
       ndefMessages = new NdefMessage[rawMsgs.length];
       for (int i = 0; i < rawMsgs.length; i++) {
         ndefMessages[i] = (NdefMessage) rawMsgs[i];
       }
     }
     if (ndefMessages != null && ndefMessages.length > 0) {
       String productId = new String(ndefMessages[0].getRecords()[0].getPayload());
       productId = productId != null ? productId.replace("en", "") : "Invalid Product tag";
       // Toast.makeText(getBaseContext(), body != null ? body.replace("en", "") : "Invalid Product
       // tag", Toast.LENGTH_LONG).show();
       productId = productId.replace(String.valueOf(productId.charAt(0)), "");
       if (!CartentiaApplication.MY_CART_PRODUCTS.contains(productId)) {
         addProductToCart(productId);
         loadAddProductFragment(productId);
       } else {
         Toast.makeText(
                 getBaseContext(), "Product is already added into your cart", Toast.LENGTH_LONG)
             .show();
       }
     } else {
       Toast.makeText(getBaseContext(), " Empty Product tag", Toast.LENGTH_LONG).show();
     }
   }
 }
示例#4
0
  @Override
  protected void onNewIntent(Intent intent) {
    toast("INTENT");
    // NDEF Exchange
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
      // vibrate(500); //Vibrate for half a secondb.
      receiveTab.append("\nWe Discovered an NDEsF tag");
      NdefMessage[] msgs = getNdefData(intent);
      if (msgs == null) {
        receiveTab.append("\nThere are NO messages");
        return;
      } else {
        receiveTab.append("\nThere ARE MESSAGES");
        Toast.makeText(this, "There are messages", Toast.LENGTH_LONG).show();
      }
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
      receiveTab.append("\nNew  Card found");
      resolveIntent(intent); // From example on mifareclassic..blogspot
    } else if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
      receiveTab.append("\nTag found from card");
      resolveIntent(intent);
    }

    // Mifare Classic Mode
    /*
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))
    {
    	vibrate(1000); //Vibrate for a second
    	Toast.makeText(this, "Mifare Type received",
    			Toast.LENGTH_LONG).show();
    }
    */
  }
示例#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
  /**
   * 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();
      }
    }
  }
示例#7
0
 @Override
 public void onResume() {
   super.onResume();
   Log.d("ANDROID_LAB", "onResume...action=" + getIntent().getAction());
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
     processIntent(getIntent());
   }
 }
示例#8
0
 @Override
 public void onResume() {
   super.onResume();
   // Check to see that the Activity started due to an Android Beam
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
     processIntent(getIntent());
   }
 }
示例#9
0
  private void resolveIntent(Intent intent) {
    String action = intent.getAction();
    toast("resolving intent");
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
      toast("RESOLVE THIS INTENT");
      Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      receiveTab.append("\nResolve Intent for NDEF discovery");
    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
      Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      MifareClassic mfc = MifareClassic.get(tagFromIntent);
      byte[] data;
      receiveTab.append("\nNew tech tag received");
      try {
        mfc.connect();
        boolean auth = false;
        String cardData = null;
        int secCount = mfc.getSectorCount();
        int bCount = 0;
        int bIndex = 0;
        for (int j = 0; j < secCount; j++) {
          auth = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT);
          if (auth) {
            bCount = mfc.getBlockCountInSector(j);
            bIndex = 0;
            for (int i = 0; i < bCount; i++) {
              bIndex = mfc.sectorToBlock(j);
              data = mfc.readBlock(bIndex);
              cardData = new String(data);
              receiveTab.append("\n" + cardData);
              bIndex++;
            }
          } else {
            Toast.makeText(this, "Auth failed", Toast.LENGTH_LONG).show();
          }
        }
      } catch (IOException ex) {
        Toast.makeText(this, "IO Error while attempting to read mifare", Toast.LENGTH_LONG).show();
      }
    } else if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
      receiveTab.append("\nSome Tag found from card");
      Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

      receiveTab.append("\n" + tagFromIntent.toString());
      for (int k = 0; k < tagFromIntent.getTechList().length; k++) {
        receiveTab.append("\nTech List: " + tagFromIntent.getTechList()[k]);
        if (tagFromIntent.getTechList()[k].equals("android.nfc.tech.NfcA")) {
          // Run connection method
          parseNfcATag(tagFromIntent);
          // connectToNDEF(tagFromIntent);
          // parseMifareTag(tagFromIntent);
        } else if (tagFromIntent.getTechList()[k].equals("android.nfc.tech.Ndef")) {
          connectToNDEF(tagFromIntent);
          // receiveTab.append("\nRun connect to NDEF");
        }
      }
    }
  }
示例#10
0
 @Override
 protected void onResume() {
   super.onResume();
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
     // only process the NFC if the activity was started by an NFC intent as
     // specified via an ACTION_NDEF_DISCOVERED
     processNFC(getIntent());
   }
 }
 private void resolveIntent(Intent intent) {
   String action = intent.getAction();
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
     byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
     id_string = ByteArrayToHexString(id);
     nouveauProduitScanne = true;
     afficherProduitsAAcheter();
   }
 }
  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);
    }
  }
 @Override
 public void onStart() {
   super.onStart();
   // Check for NFC data
   Intent i = getIntent();
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) {
     LOGI(TAG, "Badge detected");
     readTag((Tag) i.getParcelableExtra(NfcAdapter.EXTRA_TAG));
   }
   finish();
 }
示例#14
0
  /**
   * Handle intent and NFC intent
   *
   * @param intent
   */
  private void handleIntend(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {

      String type = intent.getType();
      if (NFC_MIME.equals(type)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        new NdefReaderTask().execute(tag);
      } else {
        Log.d(TAG, "Wrong mime type: " + type);
      }
    }
  }
示例#15
0
  @Override
  public ScanableTag scan() {
    Intent intent = parentActivity.getIntent();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
      return rawToScanable(rawMsgs);
    }

    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
      return new EmptyTag();
    }

    return null;
  }
示例#16
0
  protected NdefMessage[] getNdefData(Intent intent) {
    NdefMessage[] messages = null;
    String action = intent.getAction();

    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
        || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
        || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
      messages = getMessages(rawMsgs);
    } else {
      Toast.makeText(this, "Not sure which nfc type this is", Toast.LENGTH_LONG).show();
    }

    return messages;
  }
示例#17
0
 public void onResume() {
   super.onResume();
   //
   if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
     Intent intent = getIntent();
     Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
     if (rawMsgs != null) {
       NdefMessage[] msgs;
       msgs = new NdefMessage[rawMsgs.length];
       for (int i = 0; i < rawMsgs.length; i++) {
         msgs[i] = (NdefMessage) rawMsgs[i];
       }
     }
   }
   // process the msgs array
 }
  @Override
  protected void onHandleIntent(Intent intent) {
    intent = (Intent) intent.getExtras().get(NFC_INTENT);

    TimeloggerDatabaseOpenHelper databaseOpenHelper =
        new TimeloggerDatabaseOpenHelper(getApplicationContext());

    Log.d(NFC_TIMELOGGER, "handling following intent in service: " + intent.getAction());

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

      Parcelable[] ndefMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

      if (ndefMessages != null) {
        NdefMessage[] msgs = new NdefMessage[ndefMessages.length];
        for (int i = 0; i < ndefMessages.length; i++) {
          msgs[i] = (NdefMessage) ndefMessages[i];

          NdefRecord[] records = msgs[i].getRecords();
          for (NdefRecord ndefRecord : records) {
            String payload = new String(ndefRecord.getPayload());
            Log.d(NFC_TIMELOGGER, payload);
            NotificationManager notifManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            String resultAction = databaseOpenHelper.handleCategory(payload);

            Notification notification =
                new Notification.Builder(this)
                    .setContentTitle("Timelogger")
                    .setTicker(resultAction + payload)
                    .setContentText(payload)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .build();
            notifManager.notify(1234, notification);
            Log.d(NFC_TIMELOGGER, "notification sent");

            Intent updateIntent = new Intent("FRAGMENT_UPDATE");
            this.sendBroadcast(updateIntent);
          }
        }
      }
    }

    databaseOpenHelper.close();
  }
示例#19
0
  @Override
  public void onNewIntent(Intent intent) {
    nfcid = "";
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
      nfcid = this.ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
      Log.i("Huy", "NDEF DISCOVERED = " + nfcid);

    } else if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
      nfcid = this.ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID));
      Log.i("Huy", "TAG DISCOVERED = " + nfcid);

    } else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
      nfcid = this.ByteArrayToHexString(getIntent().getByteArrayExtra(NfcAdapter.EXTRA_ID));
      Log.i("Huy", "TECH DISCOVERED = " + nfcid);
    }
    setIntent(intent);
    processNfcID();
    // resolveIntent(intent);
  }
示例#20
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);
       }
     }
   }
 }
  @Override
  protected void onResume() {
    super.onResume();

    //
    if (grpMgr != null) {
      grpMgr.onResume();
    }

    // resume caused by intent from an Android Beam
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
      processNfcIntent(getIntent());
    } else {
      Closed = false;
      //
      // getPeerDeviceNetInfo();
      //
      resumeLeader();
    }
  }
  @Override
  protected void onResume() {
    super.onResume();

    Intent intent = getIntent();
    String action = intent.getAction();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
      if (rawMsgs != null) {
        NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
        for (int i = 0; i < rawMsgs.length; i++) {
          msgs[i] = (NdefMessage) rawMsgs[i];
          for (NdefRecord record : msgs[i].getRecords()) {
            String type = new String(record.getType());
            byte[] payload = record.getPayload();
            if (PROFILE_MIME_TYPE.equals(type) && payload != null && payload.length == 16) {
              handleProfileMimeType(payload);
            }
          }
        }
      }
    }
    finish();
  }
示例#23
0
  @Override
  public void onNewIntent(Intent intent) {
    Log.d("TAG", "onNewIntent");

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
      Intent in = intent;
      byte[] typ, payload;
      NdefMessage ndefMesg;
      Parcelable[] rawMsgs = in.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
      ndefMesg = (NdefMessage) rawMsgs[0];

      NdefRecord[] ndefRecords = ndefMesg.getRecords();
      int len = ndefRecords.length;
      for (int i = 0; i < len; i++) {
        typ = ndefRecords[i].getType();
        payload = ndefRecords[i].getPayload();
        tagid = getTextData(payload);
        // Toast.makeText(getApplicationContext(), tagid,Toast.LENGTH_SHORT).show();

      }

      Toast.makeText(getApplicationContext(), "Connected " + tagid, Toast.LENGTH_SHORT).show();

      array1 = loadArray("taglist", getApplicationContext());

      if (array1.length == 0) {
        String array2[] = new String[1];
        array2[0] = tagid;

        saveArray(array2, "taglist", getApplicationContext());
        array1 = loadArray("taglist", getApplicationContext());
        for (int j = 0; j < array1.length; j++) {
          Toast.makeText(getApplicationContext(), array1[j], Toast.LENGTH_SHORT).show();
        }

        Routes weather_data[] = new Routes[array1.length];
        for (int y = 0; y < array1.length; y++) {
          weather_data[y] = new Routes(array1[y], "");
        }

        RoutesAdapter adapter =
            new RoutesAdapter(Listers.this, R.layout.list_item_row_home, weather_data);

        // adapter.notifyDataSetChanged();

        ListView listView1 = (ListView) findViewById(R.id.listView12);

        //  adapter.notifyDataSetChanged();
        listView1.setAdapter(adapter);

      } else {
        String array2[] = new String[array1.length + 1];
        int h;
        for (h = 0; h < array1.length; h++) {
          array2[h] = array1[h];
        }
        array2[h] = tagid;
        saveArray(array2, "taglist", getApplicationContext());
        array1 = loadArray("taglist", getApplicationContext());
        for (int j = 0; j < array1.length; j++) {
          Toast.makeText(getApplicationContext(), array1[j], Toast.LENGTH_SHORT).show();
        }

        Routes weather_data[] = new Routes[array1.length];
        for (int y = 0; y < array1.length; y++) {
          weather_data[y] = new Routes(array1[y], "");
        }

        RoutesAdapter adapter =
            new RoutesAdapter(Listers.this, R.layout.list_item_row_home, weather_data);

        // adapter.notifyDataSetChanged();

        ListView listView1 = (ListView) findViewById(R.id.listView12);

        //  adapter.notifyDataSetChanged();
        listView1.setAdapter(adapter);
      }
      //      array1[array1.length]=tagid;

    } else {
      Toast.makeText(getApplicationContext(), "No Tag Discovered", Toast.LENGTH_SHORT).show();
    }
  }
示例#24
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.book_main);

    if (SQLHelper.GetAllBooks(this).size() <= 0) {
      //	InitDatabase();
      SQLHelper.CreateOneBook(
          this,
          "Beginning Android",
          "Mark Murphy",
          "1",
          "bookImage",
          "description",
          "1",
          "East",
          "2",
          "874512",
          "nfccode1");
      SQLHelper.CreateOneBook(
          this,
          "Android for Dummies",
          "Dan Gookin",
          "1",
          "bookImage",
          "description",
          "2",
          "West",
          "15",
          "12554",
          "nfccode2");
      SQLHelper.CreateOneBook(
          this,
          "Programming Android",
          "Laird Dornin",
          "2",
          "bookImage",
          "description",
          "3",
          "North",
          "5",
          "65155",
          "nfccode3");

      SQLHelper.CreateCategory(this, "Academic");
      SQLHelper.CreateCategory(this, "Novel");
    }

    // SQLHelper.clearDatabase(this);

    // SQLHelper.clearDatabase(getApplicationContext());
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);

    // Create the Pending Intent.
    int requestCode = 0;
    int flags = 0;

    Intent nfcIntent = new Intent(this, getClass());
    nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    nfcPendingIntent = PendingIntent.getActivity(this, requestCode, nfcIntent, flags);

    String action = getIntent().getAction();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
      try {
        processIntent(getIntent());
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
示例#25
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listers);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcPendingIntent =
        PendingIntent.getActivity(
            this,
            0,
            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
            0);
    // enableForegroundMode();

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(this.getIntent().getAction())) {

      byte[] typ, payload;
      NdefMessage ndefMesg;
      /*
      Tag myTag = (Tag) in.getParcelableExtra(NfcAdapter.EXTRA_TAG);

      Ndef ndefTag = Ndef.get(myTag);
      int size = ndefTag.getMaxSize();         // tag size
      String type = ndefTag.getType();  // tag type
       ndefMesg = ndefTag.getCachedNdefMessage();*/

      Parcelable[] rawMsgs =
          this.getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

      ndefMesg = (NdefMessage) rawMsgs[0];

      NdefRecord[] ndefRecords = ndefMesg.getRecords();
      int len = ndefRecords.length;
      for (int i = 0; i < len; i++) {
        typ = ndefRecords[i].getType();
        payload = ndefRecords[i].getPayload();
        tagid = getTextData(payload);

        Toast.makeText(getApplicationContext(), tagid + " scan again", Toast.LENGTH_SHORT).show();

        array1 = loadArray("taglist", getApplicationContext());
        //			       for(int j=0;j<array1.length;j++)
        //			       {
        //			    	   Toast.makeText(getApplicationContext(), array1[j], Toast.LENGTH_SHORT).show();
        //			       }
        if (array1.length == 0) {
          String array2[] = new String[1];
          array2[0] = tagid;

          saveArray(array2, "taglist", getApplicationContext());
          array1 = loadArray("taglist", getApplicationContext());
          for (int j = 0; j < array1.length; j++) {
            Toast.makeText(getApplicationContext(), array1[j], Toast.LENGTH_SHORT).show();
          }

          Routes weather_data[] = new Routes[array1.length];
          for (int y = 0; y < array1.length; y++) {
            weather_data[y] = new Routes(array1[y], "");
          }

          RoutesAdapter adapter =
              new RoutesAdapter(Listers.this, R.layout.list_item_row_home, weather_data);

          // adapter.notifyDataSetChanged();

          ListView listView1 = (ListView) findViewById(R.id.listView12);

          //  adapter.notifyDataSetChanged();
          listView1.setAdapter(adapter);

        } else {
          String array2[] = new String[array1.length + 1];
          int h;
          for (h = 0; h < array1.length; h++) {
            array2[h] = array1[h];
          }
          array2[h] = tagid;
          saveArray(array2, "taglist", getApplicationContext());
          array1 = loadArray("taglist", getApplicationContext());
          for (int j = 0; j < array1.length; j++) {
            Toast.makeText(getApplicationContext(), array1[j], Toast.LENGTH_SHORT).show();
          }

          Routes weather_data[] = new Routes[array1.length];
          for (int y = 0; y < array1.length; y++) {
            weather_data[y] = new Routes(array1[y], "");
          }

          RoutesAdapter adapter =
              new RoutesAdapter(Listers.this, R.layout.list_item_row_home, weather_data);

          // adapter.notifyDataSetChanged();

          ListView listView1 = (ListView) findViewById(R.id.listView12);

          //  adapter.notifyDataSetChanged();
          listView1.setAdapter(adapter);
        }
        //      array1[array1.length]=tagid;

      }
    }
  }
示例#26
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");
    }
  }
示例#27
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addplace);

    connectViewElements();

    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
      origin = 0; // NFC
      getNfcTagInfo(intent);

    } else {
      if (Intent.ACTION_SEND.equals(action) && type != null) {
        origin = 1; // Photo
        getPhotoInfo(type, intent);
      }
      // String photoPath = getIntent().getStringExtra("placePhotoPath");
      if (placePic != null) {
        Bitmap ThumbImage =
            PictureUtility.decodeSampledBitmapFromPath(
                PictureUtility.getRealPathFromURI(imageUri, SavePlace.this), 400, 400);
        placePic.setImageBitmap(ThumbImage);
      }
    }

    savePlace.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            switch (origin) {
              case 0: // nfc
                newPlace.setAudioLocation(audioLoc);
                newPlace.setNote(commentBlock.getText().toString());
                newPlace.setVideoLocation(videoLoc);

                PropertiesUtility.writePlaceToFile(v.getContext(), newPlace);
                Intent intent = new Intent(v.getContext(), ActivityMap.class);
                intent.putExtra("origin", origin);
                Places.getItems().add(newPlace);
                startActivity(intent);
                finish();
                break;
              case 1: // photo
                String picPath = PictureUtility.getRealPathFromURI(imageUri, SavePlace.this);
                int[] tempCoords =
                    PictureUtility.isCoordinatesValid(PictureUtility.getCoordsFromPhoto(picPath))
                        ? PictureUtility.getCoordsFromPhoto(picPath)
                        : currentCoordinates;
                if (PictureUtility.isCoordinatesValid(tempCoords)) {
                  newPlace = new Place(new GeoPoint(tempCoords[0], tempCoords[1]), "", "");
                  newPlace.setAudioLocation(audioLoc);
                  newPlace.setNote(commentBlock.getText().toString());
                  newPlace.setVideoLocation(videoLoc);
                  newPlace.setPhotoLocation(
                      PictureUtility.getRealPathFromURI(imageUri, SavePlace.this));
                  PropertiesUtility.writePlaceToFile(v.getContext(), newPlace);
                  Intent intent3 = new Intent(v.getContext(), ActivityMap.class);
                  Places.getItems().add(newPlace);
                  intent3.putExtra("origin", origin);
                  startActivity(new Intent(v.getContext(), HomePage.class));
                  startActivity(intent3);
                  finish();
                } else {
                  Intent intent2 = new Intent(v.getContext(), ChooseMethodForLocation.class);
                  intent2.putExtra("origin", origin);
                  startActivityForResult(intent2, 1);
                }
                break;

              default:
                System.err.println("Unknown source type");
                break;
            }
          }
        });

    recordAudio.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Button recBt = (Button) v;
            if (recBt.getText().equals(v.getResources().getString(R.string.rec_start_button))) {
              recBt.setText(v.getResources().getString(R.string.rec_stop_button));
              mRecorder = AudioUtility.getMediaRecorder();
              audioLoc = AudioUtility.startRecording(mRecorder);
            } else {
              recBt.setText(v.getResources().getString(R.string.rec_start_button));
              AudioUtility.stopRecording(mRecorder);
            }
          }
        });

    playAudio.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            if (playAudio.getText().equals(v.getResources().getString(R.string.rec_play_button))) {
              if (audioLoc.length() > 5) {
                playAudio.setText(v.getResources().getString(R.string.rec_stop_button));
                mPlayer = AudioUtility.startPlaying(audioLoc);
              }
            } else {
              playAudio.setText(v.getResources().getString(R.string.rec_play_button));
              AudioUtility.stopPlaying(mPlayer);
            }
          }
        });

    recordVideo.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            Uri fileUri = VideoUtility.getOutputMediaFileUri(VideoUtility.MEDIA_TYPE_VIDEO);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, VideoUtility.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
          }
        });

    playVideo.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            if (videoLoc.length() > 5) {
              Intent intent = new Intent(v.getContext(), PlayVideo.class);
              intent.putExtra("videoLoc", videoLoc);
              startActivityForResult(intent, 0);
            }
          }
        });
  }
示例#28
0
  private void NFCIntentMnemonicLogin() {
    final EditText edit = (EditText) findViewById(R.id.mnemonicText);

    final Intent intent = getIntent();
    if (intent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
      edit.setTextColor(Color.WHITE);
      if (intent.getType().equals("x-gait/mnc")) {
        // not encrypted nfc
        InputStream closable = null;
        try {
          closable = getAssets().open("bip39-wordlist.txt");
          final Parcelable[] rawMessages =
              intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
          final byte[] array = ((NdefMessage) rawMessages[0]).getRecords()[0].getPayload();
          final String mnemonics =
              TextUtils.join(" ", new MnemonicCode(closable, null).toMnemonic(array));
          final GaService gaService = getGAService();
          edit.setText(mnemonics);

          if (gaService != null
              && gaService.onConnected != null
              && gaService.triggerOnFullyConnected != null
              && !mnemonics.equals(gaService.getMnemonics())) {
            // Auxillary Future to make sure we are connected.
            Futures.addCallback(
                gaService.triggerOnFullyConnected,
                new FutureCallback<Void>() {
                  @Override
                  public void onSuccess(@Nullable final Void result) {
                    login();
                  }

                  @Override
                  public void onFailure(final Throwable t) {}
                });
          }

        } catch (final IOException | MnemonicException e) {
          e.printStackTrace();
        } finally {
          if (closable != null) {
            try {
              closable.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      } else if (intent.getType().equals("x-ga/en")) {
        // encrypted nfc
        final Parcelable[] rawMessages =
            intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        final byte[] array = ((NdefMessage) rawMessages[0]).getRecords()[0].getPayload();
        Futures.addCallback(
            askForPassphrase(),
            new FutureCallback<String>() {
              @Override
              public void onSuccess(@Nullable String passphrase) {
                try {
                  byte[] decrypted = decryptMnemonic(array, passphrase);
                  final GaService gaService = getGAService();
                  final String mnemonics =
                      Joiner.on(" ").join(new MnemonicCode().toMnemonic(decrypted));
                  edit.setText(mnemonics);
                  if (gaService != null
                      && gaService.onConnected != null
                      && !mnemonics.equals(gaService.getMnemonics())) {
                    Futures.addCallback(
                        gaService.onConnected,
                        new FutureCallback<Void>() {
                          @Override
                          public void onSuccess(@Nullable final Void result) {
                            login();
                          }

                          @Override
                          public void onFailure(final Throwable t) {}
                        });
                  }
                } catch (GeneralSecurityException | IOException | MnemonicException e) {
                  e.printStackTrace();
                }
              }

              @Override
              public void onFailure(Throwable t) {}
            });
      }
    }
  }
  // handles ingress intel url intents, search intents, geo intents and javascript file intents
  private void handleIntent(final Intent intent, final boolean onCreate) {
    final String action = intent.getAction();
    if (Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
      final Uri uri = intent.getData();
      Log.d("intent received url: " + uri.toString());

      if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
        if (uri.getHost() != null
            && (uri.getHost().equals("ingress.com") || uri.getHost().endsWith(".ingress.com"))) {
          Log.d("loading url...");
          loadUrl(uri.toString());
          return;
        }
      }

      if (uri.getScheme().equals("geo")) {
        try {
          handleGeoUri(uri);
          return;
        } catch (final URISyntaxException e) {
          Log.w(e);
          new AlertDialog.Builder(this)
              .setTitle(R.string.intent_error)
              .setMessage(e.getReason())
              .setNeutralButton(
                  android.R.string.ok,
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                      dialog.dismiss();
                    }
                  })
              .create()
              .show();
        }
      }

      // intent MIME type and uri path may be null
      final String type = intent.getType() == null ? "" : intent.getType();
      final String path = uri.getPath() == null ? "" : uri.getPath();
      if (path.endsWith(".user.js") || type.contains("javascript")) {
        final Intent prefIntent = new Intent(this, PluginPreferenceActivity.class);
        prefIntent.setDataAndType(uri, intent.getType());
        startActivity(prefIntent);
      }
    }

    if (Intent.ACTION_SEARCH.equals(action)) {
      String query = intent.getStringExtra(SearchManager.QUERY);
      query = query.replace("'", "''");
      final SearchView searchView = (SearchView) mSearchMenuItem.getActionView();
      searchView.setQuery(query, false);
      searchView.clearFocus();

      switchToPane(Pane.MAP);
      mIitcWebView.loadUrl("javascript:search('" + query + "');");
      return;
    }

    if (onCreate) {
      loadUrl(mIntelUrl);
    }
  }