您好我正在开发一个应用程序来读取和写入数据到 NFC 标签。我在从 NFC 标签读取数据时遇到问题。当我尝试读取数据时,我的应用程序第一次崩溃,当我第二次扫描标签时,应用程序读取数据。请帮我解决这个问题。这是我的代码。提前致谢。
public class Read extends Activity {
Tag detectedTag;
TextView txtType,txtSize,txtWrite,txtRead;
NfcAdapter nfcAdapter;
IntentFilter[] readTagFilters;
PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.read);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
nfcAdapter = NfcAdapter.getDefaultAdapter();
detectedTag =getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
txtType = (TextView) findViewById(R.id.txtType);
txtSize = (TextView) findViewById(R.id.txtsize);
txtWrite = (TextView) findViewById(R.id.txtwrite);
txtRead = (TextView) findViewById(R.id.txt_read);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(this,getClass()).
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
readTagFilters = new IntentFilter[]{tagDetected,filter2};
}
protected void onNewIntent(Intent intent) {
if(getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)){
detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
readFromTag(getIntent());
}
}
@Override
protected void onResume() {
super.onResume();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, readTagFilters, null);
}
public void readFromTag(Intent intent){
Ndef ndef = Ndef.get(detectedTag);
try{
ndef.connect();
txtType.setText(ndef.getType().toString());
txtSize.setText(String.valueOf(ndef.getMaxSize()));
txtWrite.setText(ndef.isWritable() ? "True" : "False");
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages != null) {
NdefMessage[] ndefMessages = new NdefMessage[messages.length];
for (int i = 0; i < messages.length; i++) {
ndefMessages[i] = (NdefMessage) messages[i];
}
NdefRecord record = ndefMessages[0].getRecords()[0];
byte[] payload = record.getPayload();
String text = new String(payload);
txtRead.setText(text);
ndef.close();
}
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot Read From Tag.", Toast.LENGTH_LONG).show();
}
}
}