我創建了一個獲取NFC UID並將文本視圖更改爲ID的應用程序,但是當我嘗試使用應用程序執行更多操作時,出現錯誤消息。例如,如果我嘗試說...如果UID =「001hghg」,則將另一個文本視圖更改爲「成功!」因此,我想知道是否可以先啓動應用程序,掃描標籤並在onCreate或onResume方法中更改文本視圖。這是下面的代碼:有沒有辦法在不使用onNewIntent的情況下獲得NFC UID?
public class MainActivity extends Activity {
TextView tvUID;
// list of NFC technologies detected:
private final String[][] techList = new String[][] {
new String[] {
NfcA.class.getName(),
NfcB.class.getName(),
NfcF.class.getName(),
NfcV.class.getName(),
NdefFormatable.class.getName(),
TagTechnology.class.getName(),
IsoDep.class.getName(),
MifareClassic.class.getName(),
MifareUltralight.class.getName(),
Ndef.class.getName()
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
// creating pending intent:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// creating intent receiver for NFC events:
IntentFilter filter = new IntentFilter();
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
// enabling foreground dispatch for getting intent from NFC event:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
}
@Override
protected void onNewIntent(Intent intent) {
if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
tvUID = (TextView) findViewById(R.id.tvUID);
tvUID.setText(ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));
}
}
private String ByteArrayToHexString(byte [] inarray) {
int i, j, in;
String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String out= "";
for(j = 0 ; j < inarray.length ; ++j)
{
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
out += hex[i];
i = in & 0x0f;
out += hex[i];
}
return out;
}
}
嗨,這段代碼完美的工作,它給了我的UID,但我不想使用onNewIntent,我想要的是手動啓動應用程序,然後掃描標籤,文本視圖更改爲NFC ID。整個應用程序將UID保存在數據庫中,但這將是另一個難題:( – user1697760