Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@esperia
Created August 18, 2012 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esperia/3384118 to your computer and use it in GitHub Desktop.
Save esperia/3384118 to your computer and use it in GitHub Desktop.
NFC
package com.esperia09.android.testnfc;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
private NfcAdapter mNfcAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
}
@Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
// フックするインテントフィルタを設定
IntentFilter ndefFilter = new IntentFilter(
NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefFilter.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("failure", e);
}
IntentFilter techFilter = new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] filters = new IntentFilter[] { ndefFilter, techFilter };
// NfcF(FeliCa)とNdefに反応するようにした
String[][] techLists = new String[][] {
new String[] { NfcF.class.getName() },
new String[] { Ndef.class.getName() } };
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, null,
techLists);
}
@Override
protected void onPause() {
super.onPause();
mNfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onNewIntent(Intent intent) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag != null) {
Toast.makeText(getApplicationContext(), tag.toString(),
Toast.LENGTH_SHORT).show();
// 読み取ったデータをごにょごにょする!
}
Toast.makeText(getApplicationContext(), intent.toString(),
Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment