1. The menifest file needs to be added:
<uses-permission android:name= "Android.permission.NFC"/><uses-feature android:name= " ANDROID.HARDWARE.NFC " android:required=" true "/>
Add in activity:
<intent-filter> <action android:name= "Android.nfc.action.TAG_DISCOVERED"/> <category Android:name= "Android.intent.category.DEFAULT"/></intent-filter>
2. Initialization code:
Intent nfcintent = new Intent (this, getclass ()); Nfcintent.addflags (intent.flag_activity_single_top); mpendingintent = pendingintent.getactivity (this, 0,nfcintent, 0); madapter = Nfcadapter.getdefaultadapter (this); if (Madapter = = NULL) { toast.maketext (Getapplicationcontext (), "NFC feature is supported on this device.", Toast.length_short). Show (); return;}
Functions that require override:
Private Nfcadapter Madapter; Private Pendingintent mpendingintent; @TargetApi (build.version_codes. GINGERBREAD_MR1) protected void Onresume () {super.onresume (); Madapter.enableforegrounddispatch (this, mpendingintent, NULL, NULL); } @Override protected void Onnewintent (Intent Intent) {gettaginfo (Intent); } @TargetApi (Build.version_codes. GINGERBREAD_MR1) private void Gettaginfo (Intent Intent) {tag tag = Intent.getparcelableextra (nfcadapter.extra_t AG); byte[] TagId = Tag.getid (); String str = bytearraytohexstring (tagId); str = FLIPHEXSTR (str); Long Cardno = Long.parselong (str, 16); String Ignoreoperationid = M_operationid; if (m_isonline) {//If Select all, pass in the Operation ID encoded in ticket//there should not being Many operations, take the only one new Cardvalidationasynctask (). Execute (cardno.tostring ()); }} @TargetApi (Build.version_codeS.GINGERBREAD_MR1) @Override protected void OnPause () {super.onpause (); if (madapter! = null) {Madapter.disableforegrounddispatch (this); } }
Here is the helper function:
private String Fliphexstr (string s) { StringBuilder result = new StringBuilder (); for (int i = 0; I <=s.length ()-2; i=i+2) { result.append (new StringBuilder (S.substring (i,i+2)). reverse ()); } return Result.reverse (). toString (); } Private String bytearraytohexstring (byte[] inarray) { int i, J, in; String[] Hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}; String out = ""; for (j = 0, J < inarray.length; ++j) {in = (int) inarray[j] & 0xFF; i = (in >> 4) & 0x0f; Out + = Hex[i]; i = in & 0x0f; Out + = Hex[i]; } return out; }
Android-Read the NFC card number