uni-app implements NFC reading function

uni-app implements NFC reading function

This article shares the specific code of uni-app to implement the NFC reading function for your reference. The specific content is as follows

I haven’t written a blog for a long time. Today I have the rare time to record every bit of my learning.

1. NFC method.js

//Package path const package_NdefRecord = 'android.nfc.NdefRecord';
const package_NdefMessage = 'android.nfc.NdefMessage';
const package_TECH_DISCOVERED = 'android.nfc.action.TECH_DISCOVERED';
const package_Intent = 'android.content.Intent';
const package_Activity = 'android.app.Activity';
const package_PendingIntent = 'android.app.PendingIntent';
const package_IntentFilter = 'android.content.IntentFilter';
const package_NfcAdapter = 'android.nfc.NfcAdapter';
const package_Ndef = 'android.nfc.tech.Ndef';
const package_NdefFormatable = 'android.nfc.tech.NdefFormatable';
const package_Parcelable = 'android.os.Parcelable';
const package_String = 'java.lang.String';

let NfcAdapter;
let NdefRecord;
let NdefMessage;
let readyRead = true; //Start reading let noNFC = false;
let techListsArray = [
 ['android.nfc.tech.IsoDep'],
 ['android.nfc.tech.NfcA'],
 ['android.nfc.tech.NfcB'],
 ['android.nfc.tech.NfcF'],
 ['android.nfc.tech.Nfcf'],
 ['android.nfc.tech.NfcV'],
 ['android.nfc.tech.NdefFormatable'],
 ['android.nfc.tech.MifareClassi'],
 ['android.nfc.tech.MifareUltralight']
];
// Data to be written let text = '{id:8888,name:nfc,stie:wangqin.com}';
let readResult = '';

export default {
 listenNFCStatus: function() {
  console.log("---------listenNFCStatus--------------")
  let that = this;
  try {
   let main = plus.android.runtimeMainActivity();
   let Intent = plus.android.importClass('android.content.Intent');
   let Activity = plus.android.importClass('android.app.Activity');
   let PendingIntent = plus.android.importClass('android.app.PendingIntent');
   let IntentFilter = plus.android.importClass('android.content.IntentFilter');
   NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
   let nfcAdapter = NfcAdapter.getDefaultAdapter(main);
   if (nfcAdapter == null) {
    uni.showToast({
     title: 'The device does not support NFC! ',
     icon: 'none'
    })
    noNFC = true;
    return;
   }
   if (!nfcAdapter.isEnabled()) {
    uni.showToast({
     title: 'Please enable the NFC function in the system settings first! ',
     icon: 'none'
    });
    noNFC = true;
    return;
   } else {
    noNFC = false;
   }

   let intent = new Intent(main, main.getClass());
   intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
   let pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
   let ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
   ndef.addDataType("*/*");
   let intentFiltersArray = [ndef];

   //Key code const promise = new Promise((resolve, reject) => {
    plus.globalEvent.addEventListener('newintent', function() {
     // Polling call NFC
     // setTimeout(that.nfcRuning(resolve), 1000);
     setTimeout(() => {
         that.nfcRunning(resolve)
     }, 1000);
    });
   })
   
   nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
   return promise
  } catch (e) {
  }
 },
 nfcRunning: function(resolve) {
  // console.log("--------------nfcRunning---------------")
  NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
  NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
  let main = plus.android.runtimeMainActivity();
  let intent = main.getIntent();
  let that = this;
  if (package_TECH_DISCOVERED == intent.getAction()) {
    if (readyRead) {
     //Here we get the NFC data through the read method const id = that.read(intent);
    // readyRead = false;
    //Return the data resolve(id)
   }
  }
 },
 
 read(intent) {
  // toast('Do not remove the label, data is being read');
  let that = this;
  // NFC id
  let bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
  let nfc_id = that.byteArrayToHexString(bytesId);

  return nfc_id;
 },
 byteArrayToHexString: function(inarray) { // converts byte arrays to string  
  let i, j, inn;
  let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
  let out = "";

  for (j = 0; j < inarray.length; ++j) {
   inn = inarray[j] & 0xff;
   i = (inn >>> 4) & 0x0f;
   out += hex[i];
   i = inn & 0x0f;
   out += hex[i];
  }
  return out;
 },

}

function toast(content) {
 uni.showToast({
  title: content,
  icon: 'none'
 })
}

2. Calling methods on pages using NFC

<view class="flex nfc-ewm">
  <view class="nfc-ewm-item" style="border-right: 1px solid #ccc;" @click="testNFC">
   <image src="@/assets/images/application/icon-nfc.png" alt=""></image>NFC sensing</view>
  <view class="nfc-ewm-item" @click="openScanCode">
   <image src="@/assets/images/application/icon-ewm.png" alt=""></image>QR code scanning</view>
</view>


import testtest from "../../../../../components/hexiii-nfc/hexiii-nfc.js"

 methods: {
  async testNFC() {
   //Here we use asynchronous method to get the read NFC data const nfcId = await testtest.listenNFCStatus();
   //console.log(nfcId )

   //The following data is my business logic code. If you only need to read the NFC data, the line of code above will suffice.
   const arr = []
   this.list2.forEach(e => {
    arr.push(e.code)
   })
   if(!nfcId) return
   if ( arr.indexOf(nfcId) === -1) {
    uni.showToast({
     icon: 'none',
     Title: 'No corresponding inspection point found!',
     duration: 2000
    });
   } else {
    uni.showToast({
     icon: 'none',
     title: 'Recognition successful!',
     duration: 2000
    });
    uni.navigateTo({
     url: `/pages/application/XunJianGuanLi/XunJianRenWu/KaiShiXunJian3/index?id=${this.id}&spotCode=${nfcId}&delta=${this.delta+1}`,
    });
   }
  },
}

3. Page renderings

4. Summary

The above is my implementation of reading NFC data. It automatically jumps to the corresponding check-in inspection point according to the data read by the user scanning NFC. The code needs to be improved, please give me more guidance. In the first part of the NFC method, because I only need to read the code, many redundant and unused codes have been deleted by me, leaving only the required code.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript implements cookie writing, reading, and deleting functions
  • JavaScript implements the function of reading clipboard and pasting screenshots in web pages

<<:  Detailed explanation of the use of MySQL mysqldump

>>:  How to modify Ubuntu's source list (source list) detailed explanation

Recommend

React sample code to implement automatic browser refresh

Table of contents What is front-end routing? How ...

Three ways to parse QR codes using javascript

Table of contents 1. Use JavaScript to parse the ...

How a select statement is executed in MySQL

Table of contents 1. Analyzing MySQL from a macro...

MySQL 5.7.20 free installation version configuration method graphic tutorial

I have seen many relevant tutorials on the Intern...

Linux concurrent execution is simple, just do it this way

Concurrency Functions time for i in `grep server ...

Implementation of vite+vue3.0+ts+element-plus to quickly build a project

Table of contents vite function Use Environment B...

10 skills that make front-end developers worth millions

The skills that front-end developers need to mast...

Solution to the long delay of MySQL database master-slave replication

Preface The delay of MySQL master-slave replicati...

Detailed explanation of JavaScript object conversion to primitive value

Table of contents Object.prototype.valueOf() Obje...

react+antd.3x implements ip input box

This article shares the specific code of react+an...

How to configure MySQL on Ubuntu 16.04 server and enable remote connection

background I am learning nodejs recently, and I r...

Multiple methods to modify MySQL root password (recommended)

Method 1: Use the SET PASSWORD command MySQL -u r...

MySql 8.0.16-win64 Installation Tutorial

1. Unzip the downloaded file as shown below . 2. ...