'Example'에 해당되는 글 2

  1. 2014.09.26 NFC 태그 쓰기(Write)
  2. 2013.12.26 안드로이드 공부하고싶으신분들 만들어보세요.
Android/NFC | Posted by 덩치 2014. 9. 26. 17:02

NFC 태그 쓰기(Write)

펌 OK (출처 표시), 상업적 이용 NO, 컨텐츠 변경 NO

이전 포스팅 NFC 태그 읽기 에 이어서 쓰기에 대해 알아보자


NFCWrite하기 위해서는 NDEF Message를 구성해야한다. (참고 : http://biig.tistory.com/77)


참고 글을 봤다면 NDEF Message가 어떻게 구성되는지는 다 알것이고 설명은 생략하겠다.



우선, NFC 관련 객체를 생성한다.


public static final int TYPE_TEXT = 1;

public static final int TYPE_URI = 2;


EditText mWriteText;

NfcAdapter mNfcAdapter;

PendingIntent mPendingIntent;


protected void onCreate(Bundle saveInstanceState) {


mWriteText = (EditText) findViewById(R.id.et_write);

mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

Intent inent = new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

mPendingIntent = PendingIntent.getActivity(this,0,intent,0);


}


다음, 이전 글에서 설명했듯이 태그를 인식하게되면 onNewIntent 메소드가 호출된다.


onNewIntent가 호출되면 태그에 실제로 값을 Write하는 작업을 수행해야한다.


@Override

protected void onNewIntent(Intent intent) {

super.onNewIntent(intent);

if (intent == null)

return;


Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

writeTag(getTextAsNdef(), detectedTag);


}


private NdefMessage getTextAsNdef() { 


byte[] textBytes = mWriteText.getText().toString().getBytes();


NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, 

"text/plain".getBytes(),

new byte[] {}, 

textBytes);

return new NdefMessage(new NdefRecord[] {textRecord});

}


private NdefMessage getUriAsNdef() { 


byte[] textBytes = mWriteText.getText().toString().getBytes();


NdefRecord record1 = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,

new String("U").getBytes(Charset.forName("US-ASCII")),

new byte[0],

textBytes) ;

return new NdefMessage(new NdefRecord[] {textRecord});

}


private void toast(String text) {

Log.i("fureun","toast");

Toast.makeText(this, text, Toast.LENGTH_SHORT).show();

}


이렇게 하면 기본적인 Write가 완료가 된다. 이후 Read를 하게되면 자신이 입력한 태그의 정보를 확인할 수 있다.



'Android > NFC' 카테고리의 다른 글

NFC 태그 읽기(Read)  (0) 2014.09.26
NFC란 ?  (0) 2014.09.25

펌 OK (출처 표시), 상업적 이용 NO, 컨텐츠 변경 NO

이 카테고리는 초보자를 위한 글로, 어느정도 기술력이 있다고 생각하시는분들은

해당사항이 없습니다.


무작정 책만 보고 따라하지 말고, 자신만의 과제를 정한 다음

과제를 수행하기 위한 기능들을 하나씩 검색 해 가면서 배우는것도 좋은 방법이라고 생각한다.


'뭘 만들어야할지 잘 모르겠다' 라는 경우를 위해 몇가지 간단한 유틸성 어플 과제를 제시하겠다.

'Android > 만들어보세요.' 카테고리의 다른 글

과제 - 3. wifi 매니저  (0) 2013.12.26
과제 - 2. 스탑워치  (1) 2013.12.26
과제 - 1. 심플 타마고  (2) 2013.12.26