【发布时间】:2014-03-03 21:33:27
【问题描述】:
我创建了一个应用程序,它获取 NFC UID 并将文本视图更改为 ID,但是,当我尝试对应用程序执行更多操作时,我收到一条错误消息。例如,如果我尝试说...如果 UID =“001hghg”,则将另一个文本视图更改为“成功!”因此我想知道是否可以先启动应用程序,扫描标签并在 onCreate 或 onResume 方法中更改文本视图。下面是代码:
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;
}
}
【问题讨论】:
标签: android android-intent nfc uniqueidentifier activity-lifecycle