无法正确读取NFC标签

时间:2018-04-25 14:01:47

标签: android tags nfc

每当我尝试读取NFC标签时,我总是会弄错:

if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action))

我尝试过使用不同的标签和Mifare卡,但我总是遇到同样的问题。 我不知道自己做错了什么? 感谢。

编辑:将此添加到您的manifest.xml,它将完美地工作。每当您阅读NFC标签时,该应用程序都会打开,并且会显示您的Tag的ID和技术列表。

<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>

完整代码:

 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();
     }

 } }

0 个答案:

没有答案
相关问题