androidtagsnfc

Can't read NFC tags properly


Every time I try to read a NFC tag I always got false from:

if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action))

I've tried with differents tags and Mifare cards but I always got the same problem. I'm trying to read the card and open my app in order to show the data readed. I've tried differente intent-filters and nothing seems to work Any idea of what I'm doing wrong? Thanks.

Full Code:

 public class MainActivity extends AppCompatActivity {


 private NfcAdapter nfcAdapter;
 TextView textViewInfo;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     textViewInfo = (TextView)findViewById(R.id.info);

     nfcAdapter = NfcAdapter.getDefaultAdapter(this);
     if(nfcAdapter == null){
         Toast.makeText(this,
                 "NFC NOT supported on this devices!",
                 Toast.LENGTH_LONG).show();
         finish();
     }else if(!nfcAdapter.isEnabled()){
         Toast.makeText(this,
                 "NFC NOT Enabled!",
                 Toast.LENGTH_LONG).show();
         finish();
     }
 }

 @Override
 protected void onResume() {
     super.onResume();

     Intent intent = getIntent();
    String action = intent.getAction();

     if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
         Toast.makeText(this,
                 "onResume() - ACTION_TAG_DISCOVERED",
                 Toast.LENGTH_SHORT).show();

         Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
         if(tag == null){
             textViewInfo.setText("tag == null");
         }else{
             String tagInfo = tag.toString() + "\n";

             tagInfo += "\nTag Id: \n";
             byte[] tagId = tag.getId();
             tagInfo += "length = " + tagId.length +"\n";
             for(int i=0; i<tagId.length; i++){
                 tagInfo += Integer.toHexString(tagId[i] & 0xFF) + " ";
             }
             tagInfo += "\n";

             String[] techList = tag.getTechList();
             tagInfo += "\nTech List\n";
             tagInfo += "length = " + techList.length +"\n";
             for(int i=0; i<techList.length; i++){
                 tagInfo += techList[i] + "\n ";
             }

             textViewInfo.setText(tagInfo);
         }
     }else{
         Toast.makeText(this,
                 "onResume() : " + action,
                 Toast.LENGTH_SHORT).show();
     }

 } }

Solution

  • Seems like i was missing some <intent-filter>

    These intents filters fixed my problem

        <intent-filter> <action
    android:name="android.nfc.action.NDEF_DISCOVERED" /> <category
    android:name="android.intent.category.DEFAULT" /> <data
    android:mimeType="text/plain" /> </intent-filter> <intent-filter>
    <action android:name="android.nfc.action.TAG_DISCOVERED" /> <category
    android:name="android.intent.category.DEFAULT" /> </intent-filter>