android m1卡读写

手机自带nfc功能,可用手机对m1卡进行读写,当nfc卡片贴近手机,activity需要通过onNewIntent来接收来着nfc卡片的内容,所以对m1格式nfc卡片的读写方法都是在onNewIntent中进行的,下面是读写的代码:

//重写onNewIntent方法

public void onNewIntent(Intent intent){

read(intent);//读操作

write(intent);//写操作

super.onNewIntent(inttent);


//读取m1卡数据

public void read(Intent intent){

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
boolean auth = false;
MifareClassic mifareClassic = MifareClassic.get(tag);
try {
String nfcInfo = "";
mifareClassic.connect();
int sectorCount=mifareClassic.getSectorCount();//获取m1卡扇区数,一般m1卡扇区数为16
byte bytes[]=new byte[1024*8];
int count=0;

//0扇区为m1卡id,不可更改,从1扇区读取
for (int i = 1; i auth=mifareClassic.authenticateSectorWithKeyA(i,MifareClassic.KEY_DEFAULT);//用默认密码验证i块,正确可读数据
if (auth){

//每个扇区0-2块存储数据,3块为控制块
for (int j = 0; j <3; j++) {
byte[] data=mifareClassic.readBlock(i*4+j);
for (int k = 0; k < data.length; k++) {
bytes[count++]=data[k];
}
}
}
}
nfcInfo+=new String(bytes,"UTF-8");//转换为字符串
if (nfcInfo==null||nfcInfo.equals(""))
{
Toast.makeText(this,"读取失败",Toast.LENGTH_LONG).show();
}else{

Toast.makeText(this,"数据:"+nfcInfo,Toast.LENGTH_LONG).show();

}
}catch (Exception e)
{
e.printStackTrace();
}

}

//写入数据

public void write(INtent intent){


Tag tagFormIntent=intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        MifareClassic mifareClassic=MifareClassic.get(tagFormIntent);

//验证1块,验证正确可写入

if (mifareClassic.authenticateSectorWithKeyA(1,MifareClassic.KEY_DEFAULT)){

             mifareClassic.writeBlock(4,"1234".getBytes("UTF-8"));//数据写入1扇区4块中,写入数据必须是16字节,自己补全数据

}

}

你可能感兴趣的:(android)