每次我尝试读取 NFC 标签时,我总是得到错误信息:
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action))
我尝试过不同的标签和 Mifare 卡,但总是遇到同样的问题。 我正在尝试读取该卡并打开我的应用程序以显示读取的数据。我尝试过不同的意图过滤器,但似乎没有任何效果 知道我做错了什么吗? 谢谢。
完整代码:
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();
}
} }
好像我错过了一些
<intent-filter>
这些意图过滤器解决了我的问题
<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>