nfc.plugins.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import tab from "./tab.plugins";
  2. import { settingStores } from "@/store/modules/index";
  3. var NfcAdapter;
  4. var NdefRecord;
  5. var NdefMessage;
  6. var waiting;
  7. var readyWriteData = false; //开启写
  8. var readyRead = false; //开启读
  9. var whetherNFC = false; //是否有NFC
  10. var techListsArray = [
  11. ["android.nfc.tech.IsoDep"],
  12. ["android.nfc.tech.NfcA"],
  13. ["android.nfc.tech.NfcB"],
  14. ["android.nfc.tech.NfcF"],
  15. ["android.nfc.tech.Nfcf"],
  16. ["android.nfc.tech.NfcV"],
  17. ["android.nfc.tech.NdefFormatable"],
  18. ["android.nfc.tech.MifareClassic"],
  19. ["android.nfc.tech.MifareUltralight"],
  20. ];
  21. export default {
  22. initNFC() {
  23. if (uni.getSystemInfoSync().platform == "android") {
  24. listenNFCStatus()
  25. }
  26. if (uni.getSystemInfoSync().platform == "ios") {
  27. uni.showToast({
  28. title: "设备不支持NFC!",
  29. icon: "none",
  30. });
  31. return;
  32. }
  33. },
  34. readNFC(callback) {
  35. return new Promise((resolve, reject) => {
  36. if (uni.getSystemInfoSync().platform == "android") {
  37. plus.globalEvent.addEventListener("newintent", function () {
  38. readyRead = true; //开启读
  39. plus.device.vibrate(500); //调用手机震动
  40. settingStores().nfcWaiting = '请将手机靠近NFC标签'
  41. handleNFCData().then((event) => {
  42. resolve(event)
  43. })
  44. }, false);
  45. }
  46. })
  47. },
  48. closeNFC() {
  49. if (uni.getSystemInfoSync().platform == "android") {
  50. closeReadAndWrite();
  51. }
  52. }
  53. }
  54. function listenNFCStatus() {
  55. try {
  56. var main = plus.android.runtimeMainActivity();
  57. var Intent = plus.android.importClass("android.content.Intent");
  58. var Activity = plus.android.importClass("android.app.Activity");
  59. var PendingIntent = plus.android.importClass("android.app.PendingIntent");
  60. var IntentFilter = plus.android.importClass("android.content.IntentFilter");
  61. NfcAdapter = plus.android.importClass("android.nfc.NfcAdapter");
  62. var nfcAdapter = NfcAdapter.getDefaultAdapter(main);
  63. if (nfcAdapter == null) {
  64. uni.showToast({
  65. title: "设备不支持NFC!",
  66. icon: "none",
  67. });
  68. return;
  69. }
  70. if (!nfcAdapter.isEnabled()) {
  71. uni.showToast({
  72. title: "请在系统设置中先启用NFC功能!",
  73. icon: "none",
  74. });
  75. return;
  76. }
  77. var intent = new Intent(main, main.getClass());
  78. intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  79. var pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
  80. var ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
  81. ndef.addDataType("*/*");
  82. var intentFiltersArray = [ndef];
  83. plus.globalEvent.addEventListener(
  84. "pause",
  85. function (e) {
  86. if (nfcAdapter) {
  87. //关闭前台调度系统
  88. //恢复默认状态
  89. nfcAdapter.disableForegroundDispatch(main);
  90. }
  91. },
  92. false
  93. );
  94. plus.globalEvent.addEventListener(
  95. "resume",
  96. function (e) {
  97. if (nfcAdapter) {
  98. //开启前台调度系统
  99. // 优于所有其他NFC
  100. nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
  101. }
  102. },
  103. false
  104. );
  105. nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
  106. } catch (e) {
  107. console.error(e);
  108. }
  109. }
  110. function handleNFCData() {
  111. return new Promise((resolve, reject) => {
  112. NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
  113. NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
  114. var main = plus.android.runtimeMainActivity();
  115. var intent = main.getIntent();
  116. if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {
  117. if (readyWriteData) {
  118. //__write(intent);
  119. readyWriteData = false;
  120. } else if (readyRead) {
  121. __read(intent).then((event) => {
  122. resolve(event)
  123. });
  124. readyRead = false;
  125. }
  126. }
  127. })
  128. }
  129. /**
  130. * @NFC写入
  131. * @param {*} intent
  132. * @returns
  133. */
  134. function __write(intent) {
  135. try {
  136. waiting.setTitle("请勿移开标签\n正在写入...");
  137. var text = document.getElementById("text").value;
  138. console.log("text=" + text);
  139. var textBytes = plus.android.invoke(text, "getBytes");
  140. var textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, plus.android.invoke("text/plain", "getBytes"), plus.android.invoke("", "getBytes"), textBytes);
  141. var message = new NdefMessage([textRecord]);
  142. var Ndef = plus.android.importClass("android.nfc.tech.Ndef");
  143. var NdefFormatable = plus.android.importClass("android.nfc.tech.NdefFormatable");
  144. var tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  145. var ndef = Ndef.get(tag);
  146. if (ndef != null) {
  147. var size = message.toByteArray().length;
  148. console.log("size=" + size);
  149. ndef.connect();
  150. if (!ndef.isWritable()) {
  151. showToast("tag不允许写入");
  152. waiting.close();
  153. return;
  154. }
  155. if (ndef.getMaxSize() < size) {
  156. showToast("文件大小超出容量");
  157. waiting.close();
  158. return;
  159. }
  160. ndef.writeNdefMessage(message);
  161. waiting.close();
  162. showToast("写入数据成功.");
  163. return;
  164. } else {
  165. var format = NdefFormatable.get(tag);
  166. if (format != null) {
  167. try {
  168. format.connect();
  169. format.format(message);
  170. showToast("格式化tag并且写入message");
  171. waiting.close();
  172. return;
  173. } catch (e) {
  174. showToast("格式化tag失败.");
  175. waiting.close();
  176. return;
  177. }
  178. } else {
  179. showToast("Tag不支持NDEF");
  180. waiting.close();
  181. return;
  182. }
  183. }
  184. } catch (e) {
  185. console.log("error=" + e);
  186. waiting.close();
  187. alert("写入失败");
  188. }
  189. }
  190. /**
  191. * @NFC读取
  192. * @param {*} intent
  193. * @returns
  194. */
  195. function __read(intent) {
  196. return new Promise((resolve, reject) => {
  197. try {
  198. settingStores().nfcWaiting = '请勿移开标签\n正在读取数据...'
  199. // waiting.setTitle("请勿移开标签\n正在读取数据...");
  200. var tag = plus.android.importClass("android.nfc.Tag");
  201. tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
  202. var bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
  203. // waiting.close();
  204. var tagid = bytesToHexString(tag.getId());
  205. resolve(tagid)
  206. } catch (e) {
  207. uni.showToast({
  208. title: e,
  209. icon: "none",
  210. });
  211. }
  212. })
  213. }
  214. /**
  215. * @十六进制转换
  216. * @param { 值 } inarray
  217. * @returns
  218. */
  219. function bytesToHexString(inarray) {
  220. var i, j, x;
  221. var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
  222. var out = "";
  223. for (j = 0; j < inarray.length; ++j) {
  224. x = parseInt(inarray[j]) & 0xff;
  225. i = (x >> 4) & 0x0f;
  226. out += hex[i];
  227. i = x & 0x0f;
  228. out += hex[i];
  229. }
  230. return out;
  231. }
  232. function reverseTwo(str) {
  233. var str1 = "";
  234. for (var i = 1; i <= str.length; i++) {
  235. str1 += str[i - 1];
  236. if (i % 2 == 0) {
  237. if (i == str.length) {
  238. break;
  239. }
  240. str1 += ":";
  241. }
  242. }
  243. var str2 = "";
  244. for (var i = str1.split(":").length - 1; i >= 0; i--) {
  245. str2 += str1.split(":")[i];
  246. }
  247. return str2;
  248. }
  249. if (uni.getSystemInfoSync().platform == "android") {
  250. //plus.globalEvent.addEventListener('plusready', listenNFCStatus, false);
  251. }
  252. function writeData() {
  253. var textEle = plus.globalEvent.getElementById("text");
  254. if (!textEle.value) {
  255. uni.showToast({
  256. title: "请输入要写入的内容!",
  257. icon: "none",
  258. });
  259. return;
  260. }
  261. readyWriteData = true;
  262. settingStores().nfcWaiting = '请将手机靠近NFC标签'
  263. // waiting = plus.nativeUI.showWaiting("请将手机靠近NFC标签!");
  264. }
  265. function showToast(msg) {
  266. plus.nativeUI.toast(msg);
  267. }
  268. /**
  269. * @关闭NFC
  270. */
  271. function closeReadAndWrite() {
  272. readyWriteData = false;
  273. readyRead = false;
  274. if (waiting) {
  275. waiting.close();
  276. }
  277. }