/**
* @author Flash
* 创建时间:2021-07-30 11:14
*/
public class NfcTestActivity extends AppCompatActivity {
NfcAdapter mNfcAdapter;
PendingIntent pIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_test);
initNfc();
Log.i("FlashTestNFC", "onCreate");
}
@Override
protected void onStop() {
super.onStop();
Log.i("FlashTestNFC", "onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("FlashTestNFC", "onDestroy");
}
/**
* 初始化
*/
private void initNfc(){
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
pIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
0);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.i("FlashTestNFC", "onNewIntent");
Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.i("FlashTestNFC--Tag", bytesToHex(tag.getId()));
}
@Override
protected void onResume() {
super.onResume();
Log.i("FlashTestNFC", "onResume");
if (mNfcAdapter != null) {
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] filters = new IntentFilter[]{ndef, tag, tech};
String[][] techList = new String[][]{
new String[]{
"android.nfc.tech.Ndef",
"android.nfc.tech.NfcA",
"android.nfc.tech.NfcB",
"android.nfc.tech.NfcF",
"android.nfc.tech.NfcV",
"android.nfc.tech.NdefFormatable",
"android.nfc.tech.MifareClassic",
"android.nfc.tech.MifareUltralight",
"android.nfc.tech.NfcBarcode"
}
};
mNfcAdapter.enableForegroundDispatch(this, pIntent, filters, techList);
}
}
@Override
protected void onPause() {
super.onPause();
Log.i("FlashTestNFC", "onPause");
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
/**
* 2进制to 16进制
* @param src
* @return
*/
private static String bytesToHex(byte[] src){
StringBuffer sb = new StringBuffer();
if (src == null || src.length <= 0) {
return null;
}
String sTemp;
for (int i = 0; i < src.length; i++) {
sTemp = Integer.toHexString(0xFF & src);
if (sTemp.length() < 2){
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
}