uni-app总结

发布时间:2023-08-05 18:30

内容更新时间:【2021-07-20

1、解决input输入后格式化生效问题、或闪啊闪的问题

// template


// js
changeInput() {
    this.$nextTick(() => {
        // code demo
        this.value = 0;
    });
}

2、popup弹框,底部适配及全屏(解决chrome、safari顶层遮盖)

底部适配可以参考官方论坛或者百度,修改mainif.json或者自行重写组件样式即可

全屏适配各个浏览器(主要是高度100%),重新修改组件,找到对应的class然后添加 height: 100%;

.uni-transition {
    height: 100%;
}
.uni-popup__wrapper-box {
    height: 100%;
}

3、在小程序当中,连续点击页面跳转报错

因为navigateTo在小程序当中缓存区只能存储有限个,且不会覆盖或更新
所以只能自己根据需求选择使用navigateTo或者redirectTo

4、NFC功能,onLoad中调用NFCListenAndroid,onShow中调用readData

// 包路径
const package_NdefRecord = "android.nfc.NdefRecord";
const package_NdefMessage = "android.nfc.NdefMessage";
const package_NDEF_DISCOVERED = "android.nfc.action.NDEF_DISCOVERED";
const package_TAG_DISCOVERED = "android.nfc.action.TAG_DISCOVERED";
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 main;
let waiting;
let currentNFCInfo = [];
let readyWriteData = false; // 开启写
let readyRead = false; // 开启读
let noNFC = false; // 支持NFC
const 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"],
];
export default {
    toast: function(content){
        uni.showToast({
            title: content,
            icon: "none"
        });
        // plus.nativeUI.toast(msg);
    },
    NFCInit: function() {
        let that = this;
        function judgePlatform(){
            switch ( plus.os.name ) {
                case "Android":  
                // Android平台: plus.android.*  
                that.NFCListenAndroid();
                break;
                case "iOS":  
                // iOS平台: plus.ios.*  
                that.toast("暂不支持!");
                break;
                default:  
                // 其它平台  
                that.toast("暂不支持!");
                break;
            }
        }
    },
    NFCListenAndroid: function() {
        let that = this;
        try {
            main = plus.android.runtimeMainActivity();
            let Intent = plus.android.importClass(package_Intent);
            let Activity = plus.android.importClass(package_Activity);
            let PendingIntent = plus.android.importClass(package_PendingIntent);
            let IntentFilter = plus.android.importClass(package_IntentFilter);
            NfcAdapter = plus.android.importClass(package_NfcAdapter);
            let nfcAdapter = NfcAdapter.getDefaultAdapter(main);
            // let Uri = plus.android.importClass("android.net.Uri");
            // let Bundle = plus.android.importClass("android.os.Bundle");
            // let Handler = plus.android.importClass("android.os.Handler");
            
            if (nfcAdapter == null) {
                that.toast("设备不支持NFC!");
                noNFC = true;
                return ;
            } else if (!nfcAdapter.isEnabled()) {
                that.toast("请在系统设置中先启用NFC功能!");
                noNFC = true;
                return ;
            } else {
                noNFC = false;
                // nfcAdapter.enableForegroundDispatch(main, pendingIntent, IntentFilter, techListsArray);
            }
            
            let ndef = new IntentFilter(package_NDEF_DISCOVERED);
            ndef.addDataType("*/*");
            // ndef.addDataType("/");
            let tag = new IntentFilter(package_TAG_DISCOVERED);
            let tech = new IntentFilter(package_TECH_DISCOVERED);
            let intentFiltersArray = [ndef, tag, tech];
            
            let intent = new Intent(main, main.getClass());
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            let pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
            
            plus.globalEvent.addEventListener("newintent", function() {
                console.error("newintent running");
                // 轮询调用 NFC
                setTimeout(() => { that.NFCRuning(); }, 1000);
            }, false);
            plus.globalEvent.addEventListener("pause", function(e) {
                console.error("pause running");
                if (nfcAdapter) {
                    // 关闭前台调度系统 恢复默认状态
                    nfcAdapter.disableForegroundDispatch(main);
                }
            }, false);
            plus.globalEvent.addEventListener("resume", function(e) {
                console.log("resume running");
                if (nfcAdapter) {
                    // 开启前台调度系统 优于所有其他NFC
                    nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
                }
            }, false);
            
            nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
        } catch(e){
            console.error(e);
        }
    },
    readData: function() {
        let that = this;
        if(noNFC){
            that.toast("请检查设备是否支持并开启 NFC 功能!");
            return ;
        }
        readyRead = true;
        that.toast("请将NFC标签靠近!");
        setTimeout(() => { that.NFCRuning(null); }, 1000);
    },
    writeData: function(writeBody) {
        let that = this;
        if(noNFC){
            that.toast("请检查设备是否支持并开启 NFC 功能!");
            return ;
        }
        // 轮询件
        readyWriteData = true;
        that.toast("请将NFC标签靠近!");
        setTimeout(() => { that.NFCRuning(writeBody); }, 1000);
    },
    NFCRuning: function(writeBody) {
        let that = this;
        NdefRecord = plus.android.importClass(package_NdefRecord);
        NdefMessage = plus.android.importClass(package_NdefMessage);
        // let main = plus.android.runtimeMainActivity();
        let intent = main.getIntent();
        console.log("action type:" + intent.getAction());
        if(package_TECH_DISCOVERED == intent.getAction()) {
            if(readyWriteData){
                that.NFCWrite(intent, writeBody);
                readyWriteData = false;
            } else if(readyRead){
                that.NFCRead(intent);
                readyRead = false;
            } else {
                console.log("what happend!");
            }
        }
    },
    NFCRead: function(intent) {
        let that = this;
        waiting = plus.nativeUI.showWaiting("请将NFC标签靠近!");
        waiting.setTitle("请勿移开标签\n正在读取数据...");
        try {
            let content = "";
            waiting.close();
            // let tag = plus.android.importClass("android.nfc.Tag");
            // let Parcelable = plus.android.importClass("android.os.Parcelable");
            // let rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            let rawmsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            // let tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            let tagid = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            console.log(that.ByteArray2HexString(tagid));
            //手机终端编码
            console.log(plus.device.imei);
            if (rawmsgs != null && rawmsgs.length > 0) {
                waiting.close();
                console.log(rawmsgs);
                let records = rawmsgs[0].getRecords();
                let result = records[0].getPayload();
                if (result != null) {
                    currentNFCInfo = plus.android.newObject(package_String, result);
                }
            } else {
                console.log("NFC获取失败");
                that.toast("NFC获取失败!");
            }
        } catch(e) {
            console.log("NFC获取失败,丢出异常", e);
            readyRead = true;
            waiting.close();
        }
    },
    NFCWrite: function(intent, content) {
        let that = this;
        if (!content) {
            content = {
                id: 1,
                name: nfc,
                stie: nfc.com
            };
        }
        waiting = plus.nativeUI.showWaiting("请将NFC标签靠近!");
        waiting.setTitle("请勿移开标签\n正在写入数据...");
        try{
            let textBytes = plus.android.invoke(content, "getBytes");
            // image/jpeg text/plain
            let textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, plus.android.invoke("text/plain", "getBytes"), plus.android.invoke("", "getBytes"), textBytes);
            let message = new NdefMessage([textRecord]);
            let Ndef = plus.android.importClass(package_Ndef);
            let NdefFormatable = plus.android.importClass(package_NdefFormatable);
            let tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            let ndef = Ndef.get(tag);
            if (ndef != null) {
                let size = message.toByteArray().length;
                console.log("size=" + size);
                ndef.connect();
                if (!ndef.isWritable()) {
                    that.toast("tag不允许写入");
                    waiting.close();
                    return ;
                }
                if (ndef.getMaxSize() < size) {
                    that.toast("文件大小超出容量");
                    waiting.close();
                    return ;
                }
                ndef.writeNdefMessage(message);
                waiting.close();
                that.toast("写入数据成功.");
                return ;
            } else {
                let format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);
                        that.toast("格式化tag并且写入message");
                        waiting.close();
                        return ;
                    } catch (e) {
                        that.toast("格式化tag失败.");
                        waiting.close();
                        return ;
                    }
                } else {
                    that.toast("Tag不支持NDEF");
                    waiting.close();
                    return ;
                }
            }
        } catch(e) {
            console.log("error=" + e);
            waiting.close();
            alert("写入失败");
        }
    },
    //将byte[] 转为Hex
    Bytes2HexString: function(arrBytes) {
        let that = this;
        let str = "";
        for (let i = 0; i < arrBytes.length; i++) {
            let tmp;
            let num = arrBytes[i];
            if (num < 0) {
                //Java中数值是以补码的形式存在的,应用程序展示的十进制是补码对应真值。补码的存在主要为了简化计算机底层的运算,将减法运算直接当加法来做
                tmp = (255 + num + 1).toString(16);
            } else {
                tmp = num.toString(16);
            }
            if (tmp.length == 1) {
                tmp = "0" + tmp;
            }
            str += tmp;
        }
        return str;
    },
    ByteArray2HexString: function(inarray) {
        let that = this;
        let i, j, tmp;
        let hex = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A","B", "C", "D", "E", "F" ];
        let out = "";
        console.log("here");
        for (j = 0; j < inarray.length; ++j) {
            tmp =  inarray[j] & 0xff;
            i = (tmp >> 4) & 0x0f;
            out += hex[i];
            i = tmp & 0x0f;
            out += hex[i];
        }
        return out;
    },
    readNfcV: function(intent) {
        let that = this;
        let NfcV = plus.android.importClass('android.nfc.tech.NfcV');
        let tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        // console.log(tag);
        console.log(NfcV.get(tag));
        let tech = NfcV.get(tag);
        if (tech != null) {
            try {
                tech.connect();
                console.log(tech.isConnected());
                if (tech.isConnected()) {
                    console.log('卡片字节数组ID:' + tag.getId());
                    let tagUid = tag.getId();
                    let buffer = [];
                    buffer[0] = 0x22;
                    buffer[1] = 0x23;
                    for (let i in tagUid) {
                        // console.log(tagUid[i]);
                        buffer.push(tagUid[i]);
                    }
                    buffer[10] = 0;
                    buffer[11] = 0;
                    console.log(buffer);
                    let res = tech.transceive(buffer);
                    if (res != null) {
                        console.log('标记:' + res);
                        if (String.fromCharCode(res[1]) == 'H' && String.fromCharCode(res[2]) == 'J' && String.fromCharCode(res[3]) == 'I') {
                            let blockAddress = 1;
                            let blocknum = res[4];
                            let cmd = [];
                            cmd[0] = 0x22;
                            cmd[1] = 0x23;
                            for (let i in tagUid) {
                                // console.log(tagUid[i]);
                                cmd.push(tagUid[i]);
                            }
                            cmd[10] = blockAddress & 0x0ff;
                            cmd[11] = (blocknum - 1) & 0x0ff;
                            console.log(cmd);
                            let response = tech.transceive(cmd);
                            let str = ""  
                            for(let j in response){
                                // console.log(typeof response[j])  
                                str +=this.bytesToString(response[j]);
                            }
                            console.log(str);
    
                        }
                    }
    
                }
            } catch (e) {
                //TODO handle the exception
                console.log("读取异常", e;)
            }
        } else {
            this.readNfc(intent);
        }
    },
    writeNfcV: function(intent) {
        let that = this;
        try {
            waiting = plus.nativeUI.showWaiting('请将NFC标签靠近!');
            waiting.setTitle('请勿移开标签\n正在写入...');
            // let text = document.getElementById('text').value;
            console.log('text=' + this.writeCode);
            let textBytes = plus.android.invoke(this.writeCode, 'getBytes');
            let textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, plus.android.invoke('text/plain', 'getBytes'), plus.android  
                .invoke('', 'getBytes'), textBytes);
            let message = new NdefMessage([textRecord]);
            let NfcV = plus.android.importClass('android.nfc.tech.NfcV');
            // let NdefFormatable = plus.android.importClass('android.nfc.tech.NdefFormatable');
            let tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            let nfcv = NfcV.get(tag);
            console.log('标签格式:' + nfcv);
            let bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            console.log('bytesId:' + bytesId);
            // console.log(nfcv.getTag().getId())  
            if (nfcv != null) {
                nfcv.connect();
                let size = nfcv.getMaxTransceiveLength();
                this.writeCode = '123456';//编辑内容  
                let strVal = this.writeCode;
                console.log("zijie:" + this.stringToByte(strVal))  
                let strValByte = this.stringToByte(strVal);
                console.log(strValByte.length)  
                console.log('最大字节数:' + size);
                let cmd = [];
                cmd[0] = 0x22;
                cmd[1] = 0x21;
                for (let i in bytesId) {
                    // console.log(tagUid[i]);
                    cmd.push(bytesId[i]);
                }
                console.log(cmd);
                let count = parseInt(strValByte.length + 3)/4 ;//存block数  
                console.log("count:"+count);
                let datav = new Array((count+1)*4);
                console.log("datav:"+datav)  
                // let mark = [];
                // mark[0]="72"; //H  
                // mark[1] = "74";//J  
                // mark[2] = "73";//I  
                // mark[3]=count;
                datav[0] = 72;
                datav[1] = 74;
                datav[2] = 73;
                datav[3] = count;
                // console.log("datav01:"+datav)  
                for(let j=0;j