uniapp调用Android原生NFC进行读写操作

  • 进行读操作



  •  进行写操作
write() {
				var main = plus.android.runtimeMainActivity();
				var intent = main.getIntent();
				try {
					console.log("text=" + this.writeCode);
					var textBytes = plus.android.invoke(this.writeCode, "getBytes");
					var textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
						plus.android.invoke("text", "getBytes"), plus.android.invoke("", "getBytes"), textBytes);
					var message = new NdefMessage([textRecord]);
					var Ndef = plus.android.importClass('android.nfc.tech.Ndef');
					var NdefFormatable = plus.android.importClass('android.nfc.tech.NdefFormatable');
					var tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
					var ndef = Ndef.get(tag);
					if (ndef != null) {
						var size = message.toByteArray().length;
						console.log("size=" + size);
						ndef.connect();
						if (!ndef.isWritable()) {
							console.log("tag不允许写入");
							uni.showToast({
								title: "tag不允许写入.",
								icon: "none"
							});
						}
						if (ndef.getMaxSize() < size) {
							console.log("文件大小超出容量");
							// waiting.close();
							uni.showToast({
								title: "文件大小超出容量.",
								icon: "none"
							});
							
						}
						// console.log('写入数据:' + JSON.stringify(message) + ' __TYPE__: ' + JSON.stringify(message.__TYPE__));  
						console.log("message:" + message)
						ndef.writeNdefMessage(message);

						console.log("写入数据成功.");
						uni.showToast({
							title: "写入数据成功.",
							icon: "none"
						});
					} else {
						console.log("不支持NdefFormatable写入,该方法使用需要格式化tag并且写入message")
						// var format = NdefFormatable.get(tag);
						// if (format != null) {
						// 	try {
						// 		format.connect();
						// 		format.format(message);
						// 		console.log("格式化tag并且写入message")	
						// 	} catch (e) {
						// 		console.log("格式化tag失败.");
						// 		uni.showToast({
						// 			title: "格式化tag失败.",
						// 			icon: "none"
						// 		});			
						// 	}
						// } else {
						// 	console.log("Tag不支持NDEF");
						// 	uni.showToast({
						// 		title: "Tag不支持NDEF",
						// 		icon: "none"
						// 	});
						// }
					}
				} catch (e) {
					console.log("error=" + e);
					// waiting.close();
					console.log('写入失败');
				}
			},

你可能感兴趣的:(uniapp相关,Android相关,uni-app,native,app,nfc)