Ndef.get(tag)返回null

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nongminkouhao/article/details/88428429

在使用定制android机制nfc制卡读卡开发中遇到,Ndef.get(tag)返回为null的情况;
使用场景:

  • 卡里有ndef数据的情况下(旧卡),Ndef.get(tag)返回非null
  • 卡里没有ndef数据的情况下(白卡),Ndef.get(tag)返回null

解决方案

/**
     * 写数据
     * @param ndefMessage 创建好的NDEF文本数据
     * @param tag         标签
     * @return
     */
    public static boolean writeTag(NdefMessage ndefMessage, Tag tag) {
        try {
            Ndef ndef = Ndef.get(tag);
            if(ndef==null){
                NdefFormatable format = NdefFormatable.get(tag);
                format.connect();
                format.format(ndefMessage);
                if(format.isConnected()){
                    format.close();
                }
            }else{
                ndef.connect();
                ndef.writeNdefMessage(ndefMessage);
                if(ndef.isConnected()){
                    ndef.close();
                }
            }
            return true;
        } catch (Exception e) {
            Log.d("WriteTextActivity",e.toString());
        }
        return false;
    }

如果是卡中数据已经是ndef格式,那么Ndef.get(tag)返回是有值的;如果和我的使用场景一样,使用新卡的话,那么就需要使用NdefFormatable.get(tag)进行获取;

希望对看到的朋友有帮助,如有错误还请留言指出,谢谢!

猜你喜欢

转载自blog.csdn.net/nongminkouhao/article/details/88428429