下面列出了怎么用android.nfc.NfcAdapter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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.");
}
}
@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);
}
}
/**
* 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);
}
@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;
}
}
}
/**
* {@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;
}
/** 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;
}
@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);
}
}
@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();
}
}
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);
}
}
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);
}
}
}
}
@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);
}
}
}
/**
* @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);
}
/**
* @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);
}
/**
* 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);
}
@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);
}
/**
*
* 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());
}
}
@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);
}
}
}
@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();
}
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();
}
}
}
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) {
}
}
boolean writeUri(String uri, String technology, 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 writeUriCustomHeader(uri, technology, NfcPayloadHeader.HTTP_WWW, false);
}
/**
* Enables reader mode, allowing NFC device to read / write NFC tags.
* @see android.nfc.NfcAdapter#enableReaderMode
*/
private void enableReaderModeIfNeeded() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
if (mReaderCallbackHandler != null || mActivity == null || mNfcAdapter == null) return;
// Do not enable reader mode, if there are no active push / watch operations.
if (mPendingPushOperation == null && mWatchers.size() == 0) return;
mReaderCallbackHandler = new ReaderCallbackHandler(this);
mNfcAdapter.enableReaderMode(mActivity, mReaderCallbackHandler,
NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B
| NfcAdapter.FLAG_READER_NFC_F | NfcAdapter.FLAG_READER_NFC_V,
null);
}
boolean writePhoneNumber(String phoneNumber, String technology, 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 nfcMessageUtility = mTestUtilities.determineMockType(technology);
return nfcMessageUtility != null && (readonly ? nfcMessageUtility.makeOperationReadOnly().writeTelToTagFromIntent(phoneNumber, intent) : nfcMessageUtility.writeTelToTagFromIntent(phoneNumber, intent));
}
@Override
protected void onCreateWithService(final Bundle savedInstanceState) {
setTitleWithNetwork(R.string.title_activity_sign_up);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, SignUpActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
mNfcView = UI.inflateDialog(SignUpActivity.this, R.layout.dialog_nfc_write);
mMnemonicText = UI.find(this, R.id.signupMnemonicText);
mQrCodeIcon = UI.find(this, R.id.signupQrCodeIcon);
mAcceptCheckBox = UI.find(this, R.id.signupAcceptCheckBox);
mContinueButton = UI.find(this, R.id.signupContinueButton);
mNfcSignupIcon = UI.find(this, R.id.signupNfcIcon);
mMnemonicText.setText(mService.getSignUpMnemonic());
if (mOnSignUp != null) {
UI.disable(mAcceptCheckBox);
mAcceptCheckBox.setChecked(true);
UI.enable(mContinueButton);
}
final TextView termsText = UI.find(this, R.id.textTosLink);
termsText.setMovementMethod(LinkMovementMethod.getInstance());
mQrCodeIcon.setOnClickListener(this);
mContinueButton.setOnClickListener(this);
mNfcSignupIcon.setOnClickListener(this);
mWordChoices = new ArrayList<>(24);
for (int i = 0; i < 24; ++i)
mWordChoices.add(i);
mChoiceIsValid = new boolean[VERIFY_COUNT];
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_ADAPTER_STATE_CHANGED.equals(action)) {
updateNfcState();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplication = (TimelapseApplication) getActivity().getApplication();
mDeviceManager = mApplication.getDeviceManager();
mStateMachineConnection = mApplication.getStateMachineConnection();
mNfcAdapter = NfcAdapter.getDefaultAdapter(getContext());
}
public void checkForNFCSupport() throws NfcNotSupportedException, NfcNotEnabledException {
this.nfcAdapter = NfcAdapter.getDefaultAdapter(this.context);
if (nfcAdapter == null)
throw new NfcNotSupportedException();
if (!nfcAdapter.isEnabled())
throw new NfcNotEnabledException();
}
boolean writeGeoLocation(Double latitude, Double longitude, String technology, 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 nfcMessageUtility = mTestUtilities.determineMockType(technology);
return (readonly ? nfcMessageUtility.makeOperationReadOnly().writeGeolocationToTagFromIntent(latitude, longitude, intent) : nfcMessageUtility.writeGeolocationToTagFromIntent(latitude, longitude, intent));
}
@Override
protected void onNewIntent(Intent intent) {
currentTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
binding.currentMessage.setText("NFC card detected. Please do not remove it.");
binding.nfcBg.setVisibility(View.VISIBLE);
binding.nfcBg.animate().scaleX(100).scaleY(100).setDuration(1500)
.withEndAction(this::applyNFCAction);
super.onNewIntent(intent);
}
boolean writeGeoLocation(Double latitude, Double longitude, String technology, 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 nfcMessageUtility = mTestUtilities.determineMockType(null);
return (readonly ? nfcMessageUtility.makeOperationReadOnly().writeGeolocationToTagFromIntent(latitude, longitude, intent) : nfcMessageUtility.writeGeolocationToTagFromIntent(latitude, longitude, intent));
}