2013-02-01 69 views
1

是否可以讀取然後再寫入,然後再次讀回之前我們在NFC標籤上寫入的相同數據,而無需將其從Android的移動領域(移動)中移除?如果有人已經這樣做了,那麼請分享過來....同時閱讀,寫作,然後再讀回NFC標籤可能在Android?

public class MainActivity extends Activity 
{ 
    NfcAdapter adapter; 
    PendingIntent pendingIntent; 
    IntentFilter writeTagFilters[]; 
    Tag mytag; 
    private TextView mTextViewData; 
    Context ctx; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     ctx=this; 

     mTextViewData = (TextView)findViewById(R.id.mtextView); 

     Button btnWrite = (Button) findViewById(R.id.write_button); 
     final EditText mEditText = (EditText)findViewById(R.id.edit_message); 

     adapter = NfcAdapter.getDefaultAdapter(this); 

     pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 

     IntentFilter tagDetected1 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); 

     try 
     { 
      tagDetected1.addDataType("text/nfc-service-tag"); 
     } 
     catch (MalformedMimeTypeException e) 
     { 
      throw new RuntimeException("Could not add MIME type.", e); 
     } 
     writeTagFilters = new IntentFilter[] { tagDetected1 }; 

     btnWrite.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 

        if(mytag==null) 
        { 
         Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG).show(); 
        } 
        else 
        { 
         writeTag(mEditText.getText().toString(),mytag); 

        } 

      } 
     }); 

    } 

    private void writeTag(String text,Tag tag) 
    { 
     // record to launch Play Store if app is not installed 
     // record that contains our custom "retro console" game data, using custom MIME_TYPE 
     String mimeType = "text/nfc-service-tag"; 
     byte[] payload = text.getBytes(Charset.forName("US-ASCII")); 
     byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII")); 
     NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload); 
     NdefMessage message = new NdefMessage(new NdefRecord[] { record }); 
     try 
     { 
      // see if tag is already NDEF formatted 
      Ndef ndef = Ndef.get(tag); 
      if (ndef != null) 
      { 
       ndef.connect(); 
       if (!ndef.isWritable()) 
       { 
        Toast.makeText(ctx, "Read-only tag.", Toast.LENGTH_LONG).show(); 
       } 
       // work out how much space we need for the data 
       int size = message.toByteArray().length; 
       if (ndef.getMaxSize() < size) 
       { 
        Toast.makeText(ctx, "Tag doesn't have enough free space.", Toast.LENGTH_LONG).show(); 
       } 
       ndef.writeNdefMessage(message); 
       Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG).show(); 
       ndef.close(); 
      } 
      else 
      { 
       // attempt to format tag 
       NdefFormatable format = NdefFormatable.get(tag); 
       if (format != null) 
       { 
        try 
        { 
         format.connect(); 
         format.format(message); 
         Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG).show(); 
        } 
        catch (IOException e) 
        { 
         Toast.makeText(ctx,"Unable to format tag to NDEF.", Toast.LENGTH_LONG).show(); 
        } 
       } 
       else 
       { 
        Toast.makeText(ctx,"Tag doesn't appear to support NDEF format.", Toast.LENGTH_LONG).show(); 
       } 
      } 
     } 
     catch(Exception e) 
     { 

     } 
    } 

    @Override 
    protected void onNewIntent(Intent intent) 
    { 
     String action = intent.getAction(); 
     if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) 
     { 
      NdefMessage[] msgs = getNdefMessagesFromIntent(intent); 
      final NdefMessage msg = (NdefMessage)msgs[0]; 
      String payload = new String(msg.getRecords()[0].getPayload()); 
      mTextViewData.setText(payload); 

      mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  

      Toast.makeText(this, "In onNewIntent()", Toast.LENGTH_LONG).show(); 
     } 

     else if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) 
     { 
      Toast.makeText(this, "This NFC tag has no NDEF data.", Toast.LENGTH_LONG).show(); 
     } 
    } 

    @Override 
    public void onResume() 
    { 
     super.onResume(); 
     if (getIntent().getAction() != null) 
     { 
      // tag received when app is not running and not in the foreground: 
      if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) 
      { 
       NdefMessage[] msgs = getNdefMessagesFromIntent(getIntent()); 
       NdefRecord record = msgs[0].getRecords()[0]; 
       byte[] payload = record.getPayload(); 

       String payloadString = new String(payload); 
       mTextViewData.setText(payloadString); 

       Toast.makeText(this, "In onResume()", Toast.LENGTH_LONG).show(); 

      } 
     } 
     adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null); 
    } 

    @Override 
    public void onPause() 
    { 
     super.onPause(); 
     adapter.disableForegroundDispatch(this); 
    } 

    NdefMessage[] getNdefMessagesFromIntent(Intent intent) 
    { 
     // Parse the intent 
     NdefMessage[] msgs = null; 
     String action = intent.getAction(); 
     if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) 
     { 
      Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
      if (rawMsgs != null){ 
       msgs = new NdefMessage[rawMsgs.length]; 
       for (int i = 0; i < rawMsgs.length; i++) 
       { 
        msgs[i] = (NdefMessage) rawMsgs[i]; 
       } 

      } 
      else 
      { 
       // Unknown tag type 
       byte[] empty = new byte[] {}; 
       NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty); 
       NdefMessage msg = new NdefMessage(new NdefRecord[] { record }); 
       msgs = new NdefMessage[] { msg }; 
      } 
     } 
     else 
     { 
      //Log.e(TAG, "Unknown intent."); 
      finish(); 
     } 
     return msgs; 
    }  
} 
+0

是的,這是可能的。你能更詳細地解釋你的問題嗎? –

+0

轉到這篇文章... http://stackoverflow.com/questions/12150062/android-read-back-the-tag-infomation-after-write-without-second-touch-of-tag在這裏你告訴過它是可能的....但如何?可以更詳細地解釋它.... –

+0

我在上面添加了我的完整代碼...它的讀取工作正常,然後寫入....但我想在寫入後再次讀取標記... –

回答

2

您可以撥打ndef.getNdefMessage()你做ndef.writeNdefMessage(message)後立即檢查結果。它實際上會從標籤讀取NDEF消息。但是,一般來說,當ndef.writeNdefMessage(message)未引發異常時,可以安全地假定消息已成功寫入。

+0

您是否嘗試過一個之前? –

+0

我以前用過它。 –