2015-12-08 95 views
1

我寫標籤NFC創建成功與CreateMime.How我們可以從NFC createmime值讀取的GetData字符串顯示TextView的Android的佈局值的數據?請幫助任何一個...讀取NFC從createMime在Android

@Override 
    protected void onNewIntent(Intent intent) { 
    // Tag writing mode 
    if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) { 
     Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 

     NdefRecord name = NdefRecord.createMime(((TextView)findViewById(R.id.tvname)).getText().toString(), ((TextView)findViewById(R.id.name)).getText().toString().getBytes()); 
     NdefRecord phone = NdefRecord.createMime(((TextView)findViewById(R.id.tvphone)).getText().toString(), ((TextView)findViewById(R.id.phone)).getText().toString().getBytes()); 
     NdefMessage message = new NdefMessage(new NdefRecord[] { name,phone }); 
     if (writeTag(message, detectedTag)) { 
      Toast.makeText(this, "Success: Wrote placeid to nfc tag", Toast.LENGTH_LONG) 
       .show(); 
     } 
    } 
} 

寫入一個NdefMessage到NFC標籤

public boolean writeTag(NdefMessage message, Tag tag) { 
    int size = message.toByteArray().length; 
    try { 
     Ndef ndef = Ndef.get(tag); 
     if (ndef != null) { 
      ndef.connect(); 
      if (!ndef.isWritable()) { 
       Toast.makeText(getApplicationContext(), 
       "Error: tag not writable", 
       Toast.LENGTH_SHORT).show(); 
       return false; 
      } 
      if (ndef.getMaxSize() < size) { 
       Toast.makeText(getApplicationContext(), 
       "Error: tag too small", 
       Toast.LENGTH_SHORT).show(); 
       return false; 
      } 
      ndef.writeNdefMessage(message); 
      return true; 
     } else { 
      NdefFormatable format = NdefFormatable.get(tag); 
      if (format != null) { 
       try { 
        format.connect(); 
        format.format(message); 
        return true; 
       } catch (IOException e) { 
        return false; 
       } 
      } else { 
       return false; 
      } 
     } 
    } catch (Exception e) { 
     return false; 
    } 
} 

回答

0

在你的onCreate,寫:

Intent intent=getIntent(); 

,然後調用read方法。

private void read(Intent intent) 
{ 
    try{ 
     Parcelable msgs[] = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);  
     NdefMessage msg = (NdefMessage) msgs[0]; 
     NdefRecord nameRecord = msg.getRecords()[0]; 
     NdefRecord phnoRecord = msg.getRecords()[1]; 
     String name,phno; 
     byte[] namepayload = nameRecord.getPayload(); 
     byte[] phnopayload = phnoRecord.getPayload(); 

     String textEncoding = ((namePayload[0] & 0200) == 0) ? "UTF-8" : "UTF-16"; 
     int languageCodeLength = namePayload[0] & 0077; 
     name = new String(namepayload, languageCodeLength + 1, namepayload.length - languageCodeLength - 1, textEncoding); 
     phno = new String(phnoPayload, languageCodeLength + 1, phnopayload.length - languageCodeLength - 1, textEncoding); 
     t1.setText(name); 
     t2.setText(phno); 
    } 
    catch(UnsupportedEncodingException e){} 
}