写入mifareclassic标签的问题

时间:2018-12-15 09:19:42

标签: android exception mifare

我正在尝试读写MifareClassic标签。到目前为止,我已经能够设置我的应用程序以接收前台的意图。要读取标签,我首先得到一个MifareClassic实例,对其进行身份验证并读取一个块。效果很好。

但是当我写标签时什么也没发生。该代码似乎可以正常执行,但标签上的数据没有改变。有趣的是,我尝试在未先进行身份验证的情况下写入标签。再次执行代码而不会引发任何异常。但是当我尝试读取一个未经身份验证的块时,我得到了一个异常(收发失败)。

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);


        pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        filters =  new IntentFilter[] {ndef, };
        techListsArray = new String[][] { new String[] { MifareClassic.class.getName()} };

        if(nfcAdapter!=null && nfcAdapter.isEnabled() ){}
        else{

            Toast.makeText(this, "nfc not available", Toast.LENGTH_LONG).show();
            //finish();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, techListsArray);

    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcAdapter.disableForegroundDispatch(this);

    }


protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);



    MifareClassic mfc = MifareClassic.get(tagFromIntent);
    mfc.connect();
    byte [] data2=new byte[16];
    for(int i =0;i<16;i++)
        data2[i]=0;

   //auth = mfc.authenticateSectorWithKeyA(4, key[1]);

    int blo=mfc.sectorToBlock(4);
    mfc.writeBlock(blo,data2);
    mfc.close();}

1 个答案:

答案 0 :(得分:0)

我知道了。

有问题的数据块在卡上的访问位设置为100。因此,根据MifareClassic文档的规定,为了能够写入该块,我应该使用密钥B。(但我可以读取一个块用键A)

显然,如果您使用错误的密钥对卡进行身份验证,然后调用writeblock(block,data),则不会出现异常。同时,如果您使用错误的密钥进行身份验证,然后调用readblock(block),则会收到异常。

显然,您完全不能执行身份验证,然后调用writeblock函数。而且您仍然不会例外。但不会将数据写入卡中。