마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

NFC코드 관련해서 질문드립니다.

–5 추천

아래에 첫번째,두번째,세번째 코딩 분석좀 해주세요.

완전 초보이고 공부중인데 각클래스가 ~~~해서 어떻게 구현을 해주는지 이점을 알고싶습니다.

상세하게 해주시면 완전감사하겠습니다. 대충해주셔도 상관은없습니다 ㅠㅠ


[첫번째]
package cliu.TutorialOnNFC;

import java.nio.charset.Charset;
import java.util.Locale;

import android.app.Activity;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.widget.TextView;

public class BeamData extends Activity {

private NfcAdapter mNfcAdapter;
private TextView mTextView;
private NdefMessage mNdefMessage;

@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);

setContentView(R.layout.main);
mTextView = (TextView)findViewById(R.id.tv);

mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

if (mNfcAdapter != null) {
mTextView.setText("Tap to beam to another NFC device");
} else {
mTextView.setText("This phone is not NFC enabled.");
}

// create an NDEF message with two records of plain text type
mNdefMessage = new NdefMessage(
new NdefRecord[] {
createNewTextRecord("First sample NDEF text record", Locale.ENGLISH, true),
createNewTextRecord("Second sample NDEF text record", Locale.ENGLISH, true) });
}

public static NdefRecord createNewTextRecord(String text, Locale locale, boolean encodeInUtf8) {
byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));

Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
byte[] textBytes = text.getBytes(utfEncoding);

int utfBit = encodeInUtf8 ? 0 : (1 << 7);
char status = (char)(utfBit + langBytes.length);

byte[] data = new byte[1 + langBytes.length + textBytes.length];
data[0] = (byte)status;
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);

return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}

@Override
public void onResume() {
super.onResume();

if (mNfcAdapter != null)
mNfcAdapter.enableForegroundNdefPush(this, mNdefMessage);
}

@Override
public void onPause() {
super.onPause();

if (mNfcAdapter != null)
mNfcAdapter.disableForegroundNdefPush(this);
}
}


[두번째]
package cliu.TutorialOnNFC;

import java.util.Arrays;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;

public class TagDispatch extends Activity {

private TextView mTextView;
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mIntentFilters;
private String[][] mNFCTechLists;

@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);

setContentView(R.layout.main);
mTextView = (TextView)findViewById(R.id.tv);

mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

if (mNfcAdapter != null) {
mTextView.setText("Read an NFC tag");
} else {
mTextView.setText("This phone is not NFC enabled.");
}

// create an intent with tag data and deliver to this activity
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

// set an intent filter for all MIME data
IntentFilter ndefIntent = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefIntent.addDataType("*/*");
mIntentFilters = new IntentFilter[] { ndefIntent };
} catch (Exception e) {
Log.e("TagDispatch", e.toString());
}

mNFCTechLists = new String[][] { new String[] { NfcF.class.getName() } };
}

@Override
public void onNewIntent(Intent intent) {       
String action = intent.getAction();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

String s = action + "\n\n" + tag.toString();

// parse through all NDEF messages and their records and pick text type only
Parcelable[] data = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

if (data != null) {
try {
for (int i = 0; i < data.length; i++) {
NdefRecord [] recs = ((NdefMessage)data[i]).getRecords();
for (int j = 0; j < recs.length; j++) {
if (recs[j].getTnf() == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(recs[j].getType(), NdefRecord.RTD_TEXT)) {

byte[] payload = recs[j].getPayload();
String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
int langCodeLen = payload[0] & 0077;

s += ("\n\nNdefMessage[" + i + "], NdefRecord[" + j + "]:\n\"" +
new String(payload, langCodeLen + 1,
payload.length - langCodeLen - 1, textEncoding) +
"\"");
}
}
}
} catch (Exception e) {
Log.e("TagDispatch", e.toString());
}

}

mTextView.setText(s);
}

@Override
public void onResume() {
super.onResume();

if (mNfcAdapter != null)       
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mNFCTechLists);
}

@Override
public void onPause() {
super.onPause();

if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
}


[세번째]
package cliu.TutorialOnNFC;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TutorialOnNFC extends Activity {
    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);

        setContentView(R.layout.examples);
       
        Button btag = (Button)findViewById(R.id.buttontag);
btag.setOnClickListener(new OnClickListener(){
// @Override
public void onClick(View arg0) {
startActivity(new Intent(TutorialOnNFC.this, TagDispatch.class));
}
});

Button bbeam = (Button)findViewById(R.id.buttonbeam);
bbeam.setOnClickListener(new OnClickListener(){
// @Override
public void onClick(View arg0) {
startActivity(new Intent(TutorialOnNFC.this, BeamData.class));
}
});
    }
   
    @Override
    public void onResume() {
        super.onResume();
    }
   
    @Override
    public void onPause() {
        super.onPause();
    }

} <!--/EAP_CONTENT-->

 
윤여진 (90 포인트) 님이 2013년 7월 30일 질문

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...