android.nfc.NfcAdapter Java Examples

The following examples show how to use android.nfc.NfcAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BeamController.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * If the device has NFC, construct a BeamCallback and pass it to Android.
 *
 * @param activity Activity that is sending out beam messages.
 * @param provider Provider that returns the URL that should be shared.
 */
public static void registerForBeam(final Activity activity, final BeamProvider provider) {
    final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (nfcAdapter == null) return;
    if (ApiCompatibilityUtils.checkPermission(
            activity, Manifest.permission.NFC, Process.myPid(), Process.myUid())
            == PackageManager.PERMISSION_DENIED) {
        return;
    }
    try {
        final BeamCallback beamCallback = new BeamCallback(activity, provider);
        nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
        nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
    } catch (IllegalStateException e) {
        Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
    }
}
 
Example #2
Source File: ActivityAddFriend.java    From ploggy with GNU General Public License v3.0 6 votes vote down vote up
private void setupForegroundDispatch() {
    NfcAdapter nfcAdapter = getNfcAdapter();
    if (nfcAdapter != null) {
        IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            intentFilter.addDataType(getNfcMimeType());
        } catch (IntentFilter.MalformedMimeTypeException e) {
            Log.addEntry(LOG_TAG, e.getMessage());
            return;
        }
        nfcAdapter.enableForegroundDispatch(
               this,
               PendingIntent.getActivity(
                       this,
                       0,
                       new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0),
               new IntentFilter[] {intentFilter},
               null);
    }
}
 
Example #3
Source File: NfcIdReaderActivity.java    From geopaparazzi with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    bluetoothDevice = BluetoothManager.INSTANCE.getBluetoothDevice();
    if (bluetoothDevice != null) {
        bluetoothDevice.addListener(this);
    }
    checkScanners();

    if (!inReadMode) {
        if (nfcAdapter != null && nfcAdapter.isEnabled()) {

            // Handle all of our received NFC intents in this activity.
            Intent intent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

            // Intent filters for reading a note from a tag or exchanging over p2p.
            IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
            IntentFilter[] ndefExchangeFilters = new IntentFilter[]{tagDetected};
            nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, ndefExchangeFilters, null);
        }
    }
}
 
Example #4
Source File: TabbedMainActivity.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UI.preventScreenshots(this);
    final Intent intent = getIntent();
    mIsBitcoinUri = isBitcoinScheme(intent) ||
                    intent.hasCategory(Intent.CATEGORY_BROWSABLE) ||
                    NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction());

    if (mIsBitcoinUri) {
        // Not logged in, force the user to login
        final Intent login = new Intent(this, RequestLoginActivity.class);
        startActivityForResult(login, REQUEST_BITCOIN_URL_LOGIN);
        return;
    }
    launch();
    final boolean isResetActive = getSession().isTwoFAReset();
    if (mIsBitcoinUri && !isResetActive) {
        // If logged in, open send activity
        onBitcoinUri();
    }
}
 
Example #5
Source File: NfcDetectorActivity.java    From external-nfc-api with Apache License 2.0 6 votes vote down vote up
/**
    * 
    * Process the current intent, looking for NFC-related actions
    * 
    */

public void processIntent() {
	Intent intent = getIntent();
       // Check to see that the Activity started due to an Android Beam
       if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
       	Log.d(TAG, "Process NDEF discovered action");

       	onNfcIntentDetected(IntentConverter.convert(intent), NfcAdapter.ACTION_NDEF_DISCOVERED);
       } else if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
       	Log.d(TAG, "Process TAG discovered action");

       	onNfcIntentDetected(IntentConverter.convert(intent), NfcAdapter.ACTION_TAG_DISCOVERED);
       } else  if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
       	Log.d(TAG, "Process TECH discovered action");

       	onNfcIntentDetected(IntentConverter.convert(intent), NfcAdapter.ACTION_TECH_DISCOVERED);
       } else  if (ACTION_TAG_LEFT_FIELD.equals(intent.getAction())) {
       	Log.d(TAG, "Process tag lost action");
       	
       	onNfcTagLost(IntentConverter.convert(intent)); // NOTE: This seems not to work as expected
       } else {
       	Log.d(TAG, "Ignore action " + intent.getAction());
       }
}
 
Example #6
Source File: HiddenReceiverActivity.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
@Override
    protected void onResume() {
        super.onResume();
        // Get NFC Tag intent
        Intent intent = getIntent();

        Log.d(this, intent);

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
//            String type = intent.getType();
//            Uri uri = intent.getData();
//            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            Log.d("NFC Data: " + readNfcTagPayload(intent));
            executeAction(readNfcTagPayload(intent));
        }

        // close hidden activity afterwards
        finish();
    }
 
Example #7
Source File: MainActivity.java    From amiibo with GNU General Public License v2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
protected void onNewIntent(Intent paramIntent) {
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(paramIntent.getAction())) {
        Tag tag = paramIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] uid = paramIntent.getByteArrayExtra(NfcAdapter.EXTRA_ID);


        NfcA ntag215 = NfcA.get(tag);

        if (_stack_controller != null) {
            PopableFragment popable = _stack_controller.head();
            if (popable != null) {
                if (popable instanceof ScanFragment) {
                    ((ScanFragment) popable).tryReadingAmiibo(ntag215, uid);
                } else if (popable instanceof ScanToWriteFragment) {
                    ((ScanToWriteFragment) popable).tryWriteAmiibo(ntag215, uid);
                }
            }
        }
    } else {
        setIntent(paramIntent);
    }
}
 
Example #8
Source File: AddFriendQRActivity.java    From NaviBee with GNU General Public License v3.0 6 votes vote down vote up
private void handleNfcIntent(Intent NfcIntent) {
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(NfcIntent.getAction())) {
        Parcelable[] receivedArray =
                NfcIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

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

            for (NdefRecord record: attachedRecords) {
                String string = new String(record.getPayload());
                // Make sure we don't pass along our AAR (Android Application Record)
                if (string.equals(getPackageName())) continue;
                addFriend(string);
            }
        }
    }
}
 
Example #9
Source File: TagDispatcher.java    From nordpol with MIT License 6 votes vote down vote up
/** Enable exclusive NFC access for the given activity.
 * Using this method makes NFC intent filters in the AndroidManifest.xml redundant.
 * @return NfcStatus.AVAILABLE_ENABLED if NFC was available and enabled,
 * NfcStatus.AVAILABLE_DISABLED if NFC was available and disabled and
 * NfcStatus.NOT_AVAILABLE if no NFC is available on the device.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public NfcStatus enableExclusiveNfc() {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
    if (adapter != null) {
        if (!adapter.isEnabled()) {
            if (handleUnavailableNfc) {
                toastMessage("Please activate NFC and then press back");
                activity.startActivity(new Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
            }
            return NfcStatus.AVAILABLE_DISABLED;
        }
        if (!noReaderMode && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            enableReaderMode(adapter);
        } else {
            enableForegroundDispatch(adapter);
        }
        return NfcStatus.AVAILABLE_ENABLED;
    }
    if (handleUnavailableNfc) toastMessage("NFC is not available on this device");
    return NfcStatus.NOT_AVAILABLE;
}
 
Example #10
Source File: NfcReadUtilityImpl.java    From android-nfc-lib with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public SparseArray<String> readFromTagWithSparseArray(Intent nfcDataIntent) {
    Parcelable[] messages = nfcDataIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    SparseArray<String> resultMap = messages != null ? new SparseArray<String>(messages.length) : new SparseArray<String>();

    if (messages == null) {
        return resultMap;
    }

    for (Parcelable message : messages) {
        for (NdefRecord record : ((NdefMessage) message).getRecords()) {
            byte type = retrieveTypeByte(record.getPayload());

            String i = resultMap.get(type);
            if (i == null) {
                resultMap.put(type, parseAccordingToType(record));
            }
        }
    }

    return resultMap;
}
 
Example #11
Source File: BeamActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_beam);

  // Listing 18-24: Extracting the Android Beam payload
  Parcelable[] messages
    = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
  if (messages != null) {
    NdefMessage message = (NdefMessage) messages[0];
    if (message != null) {
      NdefRecord record = message.getRecords()[0];
      String payload = new String(record.getPayload());
      Log.d(TAG, "Payload: " + payload);
    }
  }
}
 
Example #12
Source File: NfcDeviceFragment.java    From ESeal with Apache License 2.0 6 votes vote down vote up
private void enableNfcReaderMode() {
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
    if (nfcAdapter != null) {
        if (nfcAdapter.isEnabled()) {
            nfcAdapter.enableReaderMode(getActivity(), mNfcUtility, NfcUtility.NFC_TAG_FLAGS, null);
            showSnackbar(getString(R.string.text_hint_close_to_nfc_tag));
        } else {
            Snackbar snackbar = Snackbar.make(foldingCellLock, getString(R.string.error_nfc_not_open), Snackbar.LENGTH_SHORT)
                    .setAction(getString(R.string.text_hint_open_nfc), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
                            startActivity(intent);
                        }
                    });
            ((TextView) (snackbar.getView().findViewById(R.id.snackbar_text))).setTextColor(ContextCompat.getColor(getContext(), R.color.blue_grey_100));
            snackbar.show();
        }
    }
}
 
Example #13
Source File: RNHceModule.java    From react-native-nfc-hce with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if (action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
        final int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
                NfcAdapter.STATE_OFF);
        WritableMap payload = Arguments.createMap();
        switch (state) {
            case NfcAdapter.STATE_OFF:
                payload.putBoolean("status", false);
                sendEvent(reactContext, "listenNFCStatus", payload);
                break;
            case NfcAdapter.STATE_TURNING_OFF:
                break;
            case NfcAdapter.STATE_ON:
                payload.putBoolean("status", true);
                sendEvent(reactContext, "listenNFCStatus", payload);
                break;
            case NfcAdapter.STATE_TURNING_ON:
                break;
        }
    }
}
 
Example #14
Source File: BaseActivity.java    From Slide with GNU General Public License v3.0 6 votes vote down vote up
public void setShareUrl(String url) {
    try {
        if (url != null) {
            shareUrl = url;
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            if (mNfcAdapter != null) {
                // Register callback to set NDEF message
                mNfcAdapter.setNdefPushMessageCallback(this, this);
                // Register callback to listen for message-sent success
                mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
            } else {
                Log.i("LinkDetails", "NFC is not available on this device");
            }
        }
    } catch (Exception e) {

    }
}
 
Example #15
Source File: Abbott.java    From FreeStyleLibre-NFC-Reader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param activity The corresponding {@link Activity} requesting the foreground dispatch.
 * @param adapter The {@link NfcAdapter} used for the foreground dispatch.
 */
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);

    IntentFilter[] filters = new IntentFilter[1];
    String[][] techList = new String[][]{};

    // Notice that this is the same filter as in our manifest.
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);

    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
 
Example #16
Source File: NfcReaderDispatcher.java    From yubikit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Start intercepting nfc events
 * @param activity activity that is going to receive nfc events
 * Note: invoke that while activity is in foreground
 */
private void enableReaderMode(Activity activity, final NfcConfiguration nfcConfiguration) {
    NfcAdapter.ReaderCallback callback = new NfcAdapter.ReaderCallback() {
        public void onTagDiscovered(Tag tag) {
            handler.onTag(tag);
        }
    };
    Bundle options = new Bundle();
    options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 50);
    int READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B;
    if (nfcConfiguration.isDisableNfcDiscoverySound()) {
        READER_FLAGS |= NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS;
    }

    if (nfcConfiguration.isSkipNdefCheck()) {
        READER_FLAGS |= NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK;
    }
    adapter.enableReaderMode(activity, callback, READER_FLAGS, options);
}
 
Example #17
Source File: MainFlowActivity.java    From flow-android with MIT License 6 votes vote down vote up
/**
 * @param activity The activity that's requesting dispatch
 * @param adapter NfcAdapter for the current context
 */
private void enableForegroundDispatch(Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);

    IntentFilter[] filters = new IntentFilter[1];
    String[][] techList = new String[][]{};

    // Notice that this is the same filter as in our manifest.
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);
    filters[0].addDataScheme("https");
    filters[0].addDataAuthority(Constants.FLOW_DOMAIN, null);
    filters[0].addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);

    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
 
Example #18
Source File: PassportConActivity.java    From polling-station-app with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This activity usually be loaded from the starting screen of the app.
 * This method handles the start-up of the activity, it does not need to call any other methods
 * since the activity onNewIntent() calls the intentHandler when a NFC chip is detected.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();
    documentData = (DocumentData) extras.get(DocumentData.identifier);
    thisActivity = this;

    setContentView(R.layout.activity_passport_con);
    Toolbar appBar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(appBar);
    Util.setupAppBar(appBar, this);
    TextView notice = (TextView) findViewById(R.id.notice);
    progressView = (ImageView) findViewById(R.id.progress_view);

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    checkNFCStatus();
    notice.setText(R.string.nfc_enabled);
}
 
Example #19
Source File: NfcIdReaderActivity.java    From geopaparazzi with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    // NDEF exchange mode
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] idBytes = null;
        if (tag != null) {
            idBytes = tag.getId();
        } else {
            idBytes = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
        }
        String msg = getString(R.string.unable_to_read_tag_id);
        if (idBytes != null) {
            lastReadNfcMessage = Utilities.getHexString(idBytes, -1);
            msg = lastReadNfcMessage;
        } else {
            lastReadNfcMessage = ""; //$NON-NLS-1$
        }
        readMessageEditText.setText(msg);
    }

}
 
Example #20
Source File: WriteMUActivity.java    From android-nfc with MIT License 6 votes vote down vote up
@Override
public void onNewIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    String[] techList = tag.getTechList();
    boolean haveMifareUltralight = false;
    for (String tech : techList) {
        if (tech.indexOf("MifareUltralight") >= 0) {
            haveMifareUltralight = true;
            break;
        }
    }
    if (!haveMifareUltralight) {
        Toast.makeText(this, "不支持MifareUltralight数据格式", Toast.LENGTH_SHORT).show();
        return;
    }
    writeTag(tag);
}
 
Example #21
Source File: MainActivity.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
@Override
protected void onNfcIntentDetected(Intent intent, String action) {
	if(intent.hasExtra(NfcAdapter.EXTRA_ID)) {
		byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
		Log.d(TAG, "Tag id " + toHexString(id));
		
		setTagId(id);
	} else {
		Log.d(TAG, "No tag id");
		
		setTagId(null);
	}
}
 
Example #22
Source File: NFCReaderX.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void stopNFC(Activity context) {
    if (foreground_enabled) {
        try {
            NfcAdapter.getDefaultAdapter(context).disableForegroundDispatch(context);
        } catch (Exception e) {
            Log.d(TAG, "Got exception disabling foregrond dispatch");
        }
        foreground_enabled = false;
    }
}
 
Example #23
Source File: NFCReaderX.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void tagFound(Activity context, Intent data) {

        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(data.getAction())) {
            Tag tag = data.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            doTheScan(context, tag, true);
        }
    }
 
Example #24
Source File: HostConnectionProfile.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public boolean onRequest(final Intent request, final Intent response) {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(getContext());
    if (adapter != null) {
        if (adapter.isEnabled()) {
            response.putExtra(PARAM_ENABLE, true);
        } else {
            response.putExtra(PARAM_ENABLE, false);
        }
    } else {
        response.putExtra(PARAM_ENABLE, false);
    }
    setResult(response, IntentDConnectMessage.RESULT_OK);
    return true;
}
 
Example #25
Source File: WriteUriSucceedsTests.java    From android-nfc-lib with MIT License 5 votes vote down vote up
boolean writeUriCustomHeader(String uri, String technology, byte header, boolean readonly) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InsufficientCapacityException, FormatException, ReadOnlyTagException, TagNotPresentException {
    final Tag mockTag = mTestUtilities.mockTag(technology);
    final Intent intent = new Intent().putExtra(NfcAdapter.EXTRA_TAG, mockTag);
    NfcWriteUtility nfcWriteUtility = mTestUtilities.determineMockType(technology);

    return nfcWriteUtility != null && (readonly ? nfcWriteUtility.makeOperationReadOnly().writeUriWithPayloadToTagFromIntent(uri, header, intent) : nfcWriteUtility.writeUriWithPayloadToTagFromIntent(uri, header, intent));
}
 
Example #26
Source File: RunAppActivity.java    From android-nfc with MIT License 5 votes vote down vote up
@Override
public void onNewIntent(Intent intent) {
    if (mPackageName == null)
        return;
    //1.获取Tag对象
    Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    writeNFCTag(detectedTag);
}
 
Example #27
Source File: NfcReaderActivity.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
@Override
public void nfcIntentDetected(Intent intent, String action) {
	Log.d(TAG, "nfcIntentDetected: " + action);
	
	Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
	if (messages != null) {
		NdefMessage[] ndefMessages = new NdefMessage[messages.length];
	    for (int i = 0; i < messages.length; i++) {
	        ndefMessages[i] = (NdefMessage) messages[i];
	    }
	    
	    if(ndefMessages.length > 0) {
	    	// read as much as possible
			Message message = new Message();
			for (int i = 0; i < messages.length; i++) {
		    	NdefMessage ndefMessage = (NdefMessage) messages[i];
		        
				for(NdefRecord ndefRecord : ndefMessage.getRecords()) {
					try {
						message.add(Record.parse(ndefRecord));
					} catch (FormatException e) {
						// if the record is unsupported or corrupted, keep as unsupported record
						message.add(UnsupportedRecord.parse(ndefRecord));
					}
				}
		    }
			readNdefMessage(message);
	    } else {
	    	readEmptyNdefMessage();
	    }
	} else  {
		readNonNdefMessage();
	}
}
 
Example #28
Source File: ReadTextActivity.java    From android-nfc with MIT License 5 votes vote down vote up
@Override
public void onNewIntent(Intent intent) {
    //1.获取Tag对象
    Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //2.获取Ndef的实例
    Ndef ndef = Ndef.get(detectedTag);
    mTagText = ndef.getType() + "\nmaxsize:" + ndef.getMaxSize() + "bytes\n\n";
    readNfcTag(intent);
    mNfcText.setText(mTagText);
}
 
Example #29
Source File: WaitForNfcActivity.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
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)) {
        Logger.d("NFC Tag detected");
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] tag_id = tag.getId();
        Intent return_intent = new Intent();
        return_intent.putExtra(EXTRA_ID, tag_id);
        setResult(RESULT_OK, return_intent);
        Logger.v("result handed. finishing self");
        finish();
    }
}
 
Example #30
Source File: CardReaderFragment.java    From android-CardReader with Apache License 2.0 5 votes vote down vote up
private void enableReaderMode() {
    Log.i(TAG, "Enabling reader mode");
    Activity activity = getActivity();
    NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity);
    if (nfc != null) {
        nfc.enableReaderMode(activity, mLoyaltyCardReader, READER_FLAGS, null);
    }
}