Last active
December 12, 2015 04:08
-
-
Save mlc/4711691 to your computer and use it in GitHub Desktop.
nfc sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.meetup.utils; | |
import android.annotation.TargetApi; | |
import android.app.Activity; | |
import android.net.Uri; | |
import android.nfc.NdefMessage; | |
import android.nfc.NdefRecord; | |
import android.nfc.NfcAdapter; | |
import android.nfc.NfcEvent; | |
import android.os.Build; | |
public class NfcUtils { | |
public static void setBeamCallback(UriNfcSharer sharer, Activity activity) { | |
if (Build.VERSION.SDK_INT >= 14) { | |
icsSetBeamCallback(sharer, activity); | |
} | |
} | |
@TargetApi(14) | |
private static void icsSetBeamCallback(UriNfcSharer sharer, Activity activity) { | |
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity); | |
if (adapter == null) | |
return; | |
adapter.setNdefPushMessageCallback(new UriNfcCreator(sharer), activity); | |
} | |
public static interface UriNfcSharer { | |
public Uri getNfcUri(); | |
} | |
@TargetApi(14) | |
private static class UriNfcCreator implements NfcAdapter.CreateNdefMessageCallback { | |
private final UriNfcSharer sharer; | |
private UriNfcCreator(UriNfcSharer sharer) { | |
this.sharer = sharer; | |
} | |
@Override | |
public NdefMessage createNdefMessage(NfcEvent event) { | |
final Uri uri = sharer.getNfcUri(); | |
if (uri == null) { | |
return null; | |
} else { | |
return new NdefMessage(new NdefRecord[] { | |
NdefRecord.createUri(uri), | |
NdefRecord.createApplicationRecord("com.meetup") | |
}); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SampleActivity extends Activity { | |
@Override | |
protected void onCreate(Bundle icicle) { | |
// ... | |
NfcUtils.setBeamCallback(new NfcCallback(), this); | |
} | |
public class NfcCallback implements NfcUtils.UriNfcSharer { | |
@Override | |
public Uri getNfcUri() { | |
Uri.Builder bld = Uri.parse("http://www.meetup.com/members/").buildUpon() | |
.appendPath(getMemberId()); | |
final String groupId = getGroupId(); | |
if (groupId != null) | |
bld.appendQueryParameter("groupId", groupId); | |
return bld.build(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment