In order to explain NFC thoroughly, I will use three methods to explain it in detail and gradually understand the code writing. This is the first method.
Not much to say, this time the main demonstration is to read the card number of the contactless IC card through NFC. Mainly divided into 3 steps:
(1) Configure permissions and use nfc
(2) Main process of calling NFC
(3) Code examples
(1) Configuration permissions
Add the following code to AndroidMainfest.xml
<!--NFC permissions--> <uses-permission android:name="android.permission.NFC" /> <!-- The current device must have an NFC chip --> <uses-feature android:name="android.hardware.nfc" android:required="true" />
(2) Main process of calling NFC
The main class object used when using nfc is: NfcAdapter. We understand it as our nfc device, which is generally defined as a static variable and adopts singleton mode. Because a device only has one NFC reader.
Object | Event | Content | Key code |
activity object | onStart |
//Initialize Nfc object |
mNfcAdapter = NfcAdapter.getDefaultAdapter(context);//NfcAdapter object of the device |
activity object |
onResume |
//Start scanning when activity is activated |
mNfcAdapter.enableReaderMode |
activity object |
onPause |
< pre> //Stop scanning when the activity switches to the background |
mNfcAdapter.disableReaderMode |
NFC object |
NfcListener |
//What to do when a card is scanned. |
The callback function is triggered here. |
Note that the first three are events of the activity object. The fourth one is the event of nfc object.
(3) Code display
Mainly contains two categories
NfcUtil mainly encapsulates the singleton mode and the implementation of the four methods mentioned in the table above.
package com.apep.nfctest; import android.app.Activity; import android.content.Context; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.util.Log; import android.widget.Toast; /** * Created by Administrator on 2023/11/10. */ public class NfcUtils { private static final String TAG = "NfcUtils"; private static NfcAdapter mNfcAdapter; private NfcUtils(){} private static NfcUtils nfcUtils = null; private static boolean isOpen = false; /** * Get the singleton instance of NFC * @return NfcUtils */ public static NfcUtils getInstance(){ if (nfcUtils == null){ synchronized (NfcUtils.class){ if (nfcUtils == null){ nfcUtils = new NfcUtils(); } } } return nfcUtils; } /** * Check whether nfc function is supported in onStart * @param context current page context */ public void onStartNfcAdapter(Context context){ mNfcAdapter = NfcAdapter.getDefaultAdapter(context);//NfcAdapter object of the device if(mNfcAdapter==null){//Determine whether the device supports the NFC function Toast.makeText(context,"The device does not support NFC function!",Toast.LENGTH_SHORT).show(); return; } if (!mNfcAdapter.isEnabled()){//Determine whether the device NFC function is turned on Toast.makeText(context,"Please go to the system settings to turn on the NFC function!",Toast.LENGTH_SHORT).show(); return; } Log.d(TAG,"NFC is start"); } /** * Enable nfc function in onResume * @param activity */ public void onResumeNfcAdapter(final Activity activity){ if (mNfcAdapter!=null & amp; & amp; mNfcAdapter.isEnabled()){ // mNfcAdapter.enableForegroundDispatch(this,mPendingIntent,null,null);//Open the foreground publishing system to make the page superior to other nfc processing. When a Tag tag is detected, mPendingItent will be executed if (!isOpen) mNfcAdapter.enableReaderMode(activity, new NfcAdapter.ReaderCallback() { @Override public void onTagDiscovered(final Tag tag) { //ByteArrayToHexString(tag.getId()) is cardId Log.d(TAG,ByteArrayToHexString(tag.getId())); if (nfcListener != null) (activity).runOnUiThread(new Runnable() { @Override public void run() { nfcListener.doing(tag); } }); } }, (NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B | NfcAdapter.FLAG_READER_NFC_F | NfcAdapter.FLAG_READER_NFC_V | NfcAdapter.FLAG_READER_NFC_BARCODE), null); isOpen = true; Log.d(TAG,"Resume"); } } /** * Turn off nfc function in onPause * @param activity */ public void onPauseNfcAdapter(Activity activity){ if(mNfcAdapter!=null & amp; & amp; mNfcAdapter.isEnabled()){ if(isOpen) mNfcAdapter.disableReaderMode(activity); isOpen = false; } Log.d("myNFC","onPause"); } private NfcListener nfcListener; public void setNfcListener(NfcListener listener){ nfcListener = listener; } /** * Customized NFC interface */ public interface NfcListener{ /** * Used for subsequent operations after scanning nfc */ void doing(Tag tag); } public 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] & amp; 0xff; i = (in >> 4) & amp; 0x0f; out + = hex[i]; i = in & 0x0f; out + = hex[i]; } return out; } }
MainActivity, the code of the main form is embedded in NfcUtils
package com.apep.nfctest; import android.nfc.Tag; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements NfcUtils.NfcListener{ private NfcUtils nfcUtils = NfcUtils.getInstance(); private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); nfcUtils.setNfcListener(this); } @Override protected void onStart() { super.onStart(); nfcUtils.onStartNfcAdapter(this); //Initialize the Nfc object } @Override protected void onResume() { super.onResume(); nfcUtils.onResumeNfcAdapter(this); //Start scanning when activity is activated } @Override protected void onPause() { super.onPause(); nfcUtils.onPauseNfcAdapter(this); //Stop scanning when the activity switches to the background } @Override public void doing(Tag tag) { textView.setText(nfcUtils.ByteArrayToHexString(tag.getId())); //What to do when the card is scanned. } }
Everyone can save trouble, just create two classes according to the picture, paste the code and you can use it. The only thing to note is to add a textbox and add this object to R.id.