【发布时间】:2013-12-09 04:05:44
【问题描述】:
我正在尝试在 on create 方法中获取 NFC 标签的唯一 ID。我已经使用名为“onNewIntent”的覆盖方法成功完成了这项工作,但是我想在 oncreate 方法中获取它。这是我尝试过的,我手机上的应用程序在启动时崩溃了。请任何人都可以帮忙。谢谢。
public class MainActivity extends Activity {
TextView uid;
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);
uid = (TextView) findViewById(R.id.UID);
Intent i = new Intent();
IntentFilter filter = new IntentFilter();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
if (i.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
((TextView)findViewById(R.id.UID)).setText(ByteArrayToHexString(i.getByteArrayExtra(NfcAdapter.EXTRA_ID)));
}
}
private String ByteArrayToHexString(byte [] inarray) { //converts byte arrays to string
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;
}
}
【问题讨论】:
-
发布 logcat 输出。
-
好的,基本上我创建了一个新的意图。我从设备中获取了默认的 NFC 硬件。如果发现标签,则应将 textview 更改为 NFC 标签的 ID
标签: android nfc uniqueidentifier oncreate