此代码简单实现了TECH标准NFC读操作
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this;
//检查NFC权限
NfcCheck();
mPendingIntent=PendingIntent.getActivity(this,0,
new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
}
private void enableForegroudDispatch(){
if(mNfcAdapter!=null){
mNfcAdapter.enableForegroundDispatch(this,mPendingIntent,null,null);
}
}
private void disableForegroudDispatch(){
if(mNfcAdapter!=null){
mNfcAdapter.disableForegroundDispatch(this);
}
}
@Override
protected void onResume() {
super.onResume();
enableForegroudDispatch();
}
@Override
protected void onPause() {
super.onPause();
disableForegroudDispatch();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
resolveIntent(intent);
}
上述代码是安卓生命周期重写的相关代码。
//检查NFC权限
private void NfcCheck(){
mNfcAdapter=NfcAdapter.getDefaultAdapter(this);
if(mNfcAdapter==null){
Toast.makeText(mContext,"您的手机不支持NFC",Toast.LENGTH_LONG);
finish();
}else{
if(!mNfcAdapter.isEnabled()){
Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivity(setNfc);
return;
}
}
}
//是否支持标签类型
private boolean supportedTechs(String[] techList) {
boolean isSupport=false;
for(String s:techList){
if(s.equals("android.nfc.tech.MifareClassic")){
isSupport=true;
}
else if(s.equals("android,nfc.tech.MifareUltralight")){
isSupport=true;
}else if(s.equals("android,nfc.tech.Ndef")){
isSupport=true;
}else if(s.equals("android,nfc.tech.IsoDep")){
isSupport=true;
}else if(s.equals("android,nfc.tech.NfcA")){
isSupport=true;
}
else{
isSupport=true;
}
}
return isSupport;
}
//对标签进行处理
public void resolveIntent(Intent intent){
String action = intent.getAction();
Tag tag=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Boolean isAuth=false;
if(supportedTechs(tag.getTechList())){
MifareClassic mfc=MifareClassic.get(tag);
if(mfc!=null){
try {
mfc.connect();
int nSecont =mfc.getSectorCount();
for(int i=0;i<nSecont;i++){
if(mfc.authenticateSectorWithKeyA(i,MifareClassic.KEY_DEFAULT)){
isAuth=true;
Log.e("扇区号",":"+i);
}else{
isAuth=false;
Log.e("密码错误","密码错误");
}
if(isAuth){
int nBlock=mfc.getBlockCountInSector(i);
StringBuilder data1=new StringBuilder();
for(int j=0;j<nBlock;j++){
byte[] data=mfc.readBlock(j);
data1.append(data);
Log.i("SkySeraph","data"+j+"="+data);
}
payloadTV.setText(data1);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.e("SkySeraph","不是MifareClassic");
}
}
}
以上代码运行时没有问题,但是加入到我其他的项目中就会出现NFC标签重复扫描问题,只要标签不离开手机,手机就会一直响(扫描),后面继续寻找问题。