Skip to content

Instantly share code, notes, and snippets.

@esperia
Created December 15, 2012 03:20
Show Gist options
  • Save esperia/4291050 to your computer and use it in GitHub Desktop.
Save esperia/4291050 to your computer and use it in GitHub Desktop.
IDmを読み取るためのシンプルな実装例
package com.esperia09.android.readnfc;
import java.util.Formatter;
import java.util.Locale;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.widget.TextView;
public class BasicNfcSampleActivity extends Activity {
private NfcAdapter mNfcAdapter;
private TextView mTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mTxt = (TextView) findViewById(R.id.txt);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
mNfcAdapter.enableForegroundDispatch(this, pIntent, null, null);
}
@Override
protected void onPause() {
super.onPause();
mNfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
byte[] idm = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
String idmStr = bytesToHexString(idm);
mTxt.setText(idmStr);
// IDmをハッシュ化とかしてサーバへデータを送信
setIntent(null);
}
/*
* バイト列を16進数文字列に変換
*/
public static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
formatter.close();
return sb.toString().toUpperCase(Locale.getDefault());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment