NFC URL WIRTE
------------------------------------------------------------------------------------
.
.
.
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent == null)
return;
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String writeValue = "http://www.naver.com";
NdefMessage message = createTagMessage(writeValue);
writeTag(message, detectedTag);
}
private NdefMessage createTagMessage(String msg) {
NdefMessage mMessage = new NdefMessage(NdefRecord.createUri(msg));
return mMessage;
}
public void 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(), "can not write NFC tag",
Toast.LENGTH_SHORT).show();
}
if (ndef.getMaxSize() < size) {
Toast.makeText(getApplicationContext(),
"NFC tag size too large", Toast.LENGTH_SHORT).show();
}
ndef.writeNdefMessage(message);
Toast.makeText(getApplicationContext(),
"NFC tag is writted", Toast.LENGTH_SHORT).show();
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
try {
format.connect();
format.format(message);
Toast.makeText(getApplicationContext(), "NFC tag is formatting",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
}
} else {
}
}
} catch (Exception e) {
}
}
.
.
.
------------------------------------------------------------------------------------
NFC URL READ
------------------------------------------------------------------------------------
.
.
.
@Override
public void onNewIntent(Intent intent) {
Parcelable[] messages = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages == null)
return;
for (int i = 0; i < messages.length; i++)
showMsg((NdefMessage) messages[i]);
}
public void showMsg(NdefMessage mMessage) {
NdefRecord[] recs = mMessage.getRecords();
for (int i = 0; i < recs.length; i++) {
NdefRecord record = recs[i];
if (Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
Uri u = record.toUri();
Intent j = new Intent(Intent.ACTION_VIEW);
j.setData(u);
startActivity(j);
finish();
}
}
------------------------------------------------------------------------------------
AndroidManifest.xml
------------------------------------------------------------------------------------
<activity
android:name=".NfcReader"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
'안드로이드' 카테고리의 다른 글
java 공휴일 체크 (0) | 2015.01.15 |
---|---|
현재 위도 경도를 주소로 변환 (0) | 2015.01.06 |
ListView did not receive a notification 오류 해결법 (0) | 2014.11.13 |
Seekbar 볼륨 조절 AlertDialog 이용 (0) | 2014.10.08 |
Android GCM JSP 연동 예제 (2) (1) | 2014.08.20 |