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

How to change apt-get source in Ubuntu 18.04

When using apt-get to install, it will be very sl...

How to view and terminate running background programs in Linux

Linux task management - background running and te...

CSS+HTML to realize the top navigation bar function

Implementation of navigation bar, fixed top navig...

Vue code highlighting plug-in comprehensive comparison and evaluation

Table of contents Comprehensive comparison From t...

JavaScript implements the nine-grid mobile puzzle game

This article shares the specific code for JavaScr...

The meaning of status code in HTTP protocol

A status code that indicates a provisional respon...

Introduction to general_log log knowledge points in MySQL

The following operation demonstrations are all ba...

Summary of tips for setting the maximum number of connections in MySQL

Method 1: Command line modification We only need ...

About the problem of vertical centering of img and span in div

As shown below: XML/HTML CodeCopy content to clip...

MySQL query syntax summary

Preface: This article mainly introduces the query...

Implementation of services in docker accessing host services

Table of contents 1. Scenario 2. Solution 3. Conc...

Detailed explanation of CSS style cascading rules

CSS style rule syntax style is the basic unit of ...

A brief discussion on CSS3 animation jamming solutions

Why is it stuck? There is a premise that must be ...

Solution to the problem of slow docker pull image speed

Currently, Docker has an official mirror for Chin...