1***@qq.com
1***@qq.com
  • 发布:2023-04-22 23:44
  • 更新:2024-07-17 11:44
  • 阅读:864

uniapp读取NFC标签,鸿蒙2能行,安卓12就不行

分类:uni-app
NFC

同样的代码,为什么安卓12的系统就失败。

大家好,下面的代码,在我的荣耀10(鸿蒙2)上能成功读取ID,但在荣耀50和小米13上面都是一直在转,读不了,并且系统会一直提示选择NFC服务软件,导致读取失败,麻烦哪位大神帮忙看看.

下面是我程序使用的代码,例子也可以参考 这个 ,在手机上的效果也是一样的!

附件中是手机的演示视频。

var NfcAdapter;  
var NdefRecord;  
var NdefMessage;  
var _getCardNo;  
var waiting;  
var readyWriteData = false;  
var readyRead = false;  

export default {  
    initNFC() {  
        if (uni.getSystemInfoSync().platform == 'android') {  
            listenNFCStatus();  
        }  
    },  
    readNFC(callback) {  
        if (uni.getSystemInfoSync().platform == 'android') {  
            readData(callback);  
        }  
    },  
    closeNFC() {  
        if (uni.getSystemInfoSync().platform == 'android') {  
            closeReadAndWrite();  
        }  
    }  
}  

function listenNFCStatus() {  
    try {  
        var main = plus.android.runtimeMainActivity();  
        var Intent = plus.android.importClass('android.content.Intent');  
        var Activity = plus.android.importClass('android.app.Activity');  
        var PendingIntent = plus.android.importClass('android.app.PendingIntent');  
        var IntentFilter = plus.android.importClass('android.content.IntentFilter');  
        NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');  
        var nfcAdapter = NfcAdapter.getDefaultAdapter(main);  

        if (nfcAdapter == null) {  
            uni.showToast({  
                title: '设备不支持NFC!',  
                icon: 'none'  
            })  
            return;  
        }  

        if (!nfcAdapter.isEnabled()) {  
            uni.showToast({  
                title: '请在系统设置中先启用NFC功能!',  
                icon: 'none'  
            });  
            return;  
        }  

        var intent_ = new Intent(main, main.getClass());  
        intent_.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);  
        var pendingIntent = PendingIntent.getActivity(main, 0, intent_, 0);  

        var ndef = new IntentFilter("android.nfc.action.NDEF_DISCOVERED"); //NfcAdapter.ACTION_NDEF_DISCOVERED  
        var tag = new IntentFilter("android.nfc.action.TAG_DISCOVERED"); //NfcAdapter.ACTION_TECH_DISCOVERED  
        var tech = new IntentFilter("android.nfc.action.TECH_DISCOVERED");  
        var intentFiltersArray = [ndef, tag, tech];  

        ndef.addDataType("*/*");  

        var 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.net.Uri'],  
                ['android.nfc.tech.NdefFormatable'],  
                ['android.nfc.tech.MifareClassi'],  
                ['android.nfc.tech.MifareUltralight']  
            ];  

        plus.globalEvent.addEventListener("newintent",  
            function() {  
                setTimeout(handle_nfc_data1, 1000);  
            }, false);  
        plus.globalEvent.addEventListener("pause", function(e) {  
            if (nfcAdapter) {  
                nfcAdapter.disableForegroundDispatch(main);  
            }  
        }, false);  
        plus.globalEvent.addEventListener("resume", function(e) {  
            if (nfcAdapter) {  
                //console.log('resume');   
                nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);  
            }  
        }, false);  

        nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);  
    } catch (e) {  
        console.error(e);  
        showToast(e);  
    }  
}  

function handle_nfc_data1() {  
    NdefRecord = plus.android.importClass("android.nfc.NdefRecord");  
    NdefMessage = plus.android.importClass("android.nfc.NdefMessage");  
    var main = plus.android.runtimeMainActivity();  
    var intent = main.getIntent();  
    //console.log("action type:" + intent.getAction());   
    if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {  
        if (readyWriteData) {  
            //__write(intent);  
            readyWriteData = false;  
        }   
        if (readyRead) {  
            __read(intent);  
            //readyRead = false;  
            // showToast("读取完成");  
        }  
    }  
}  

function showToast(msg) {  
    if (typeof plus !== 'undefined') {  
      plus.nativeUI.toast(msg)  
    } else {  
      // 为了方便在浏览器中调试  
      uni.showToast({  
        title: msg,  
        duration: 2000,  
        icon: 'none',  
      })  
    }  
}  

function __read(intent) {  
    try {  
        var content = "";  
        waiting.setTitle('请勿移开标签\n正在读取数据...');  
        var main = plus.android.runtimeMainActivity();  
        var _intent = main.getIntent();  
        var _action = _intent.getAction();  
        if (  
            NfcAdapter.ACTION_NDEF_DISCOVERED == _action ||  
            NfcAdapter.ACTION_TAG_DISCOVERED == _action ||  
            NfcAdapter.ACTION_TECH_DISCOVERED == _action  
        ) {  
            var tag = _intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);  
            waiting.close();  
            var tagid = bytesToHexString(tag);  
            tagid = prefixInteger(hex2int(tagid), 10);  
            if (typeof _getCardNo === 'function') {  
                _getCardNo(tagid);  
            }  
        }else{  
            showToast('读取失败');  
            waiting.close();  
        }  
    } catch (e) {  
        showToast(e);  
        waiting.close();  
    }  
}  

function bytesToHexString(inarray) {  
    var i, j, x;  
    var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",  
        "B", "C", "D", "E", "F"  
    ];  
    var out = "";  
    for (j = 0; j < inarray.length; ++j) {  
        x = parseInt(inarray[j]) & 0xff;  
        i = (x >> 4) & 0x0f;  
        out += hex[i];  
        i = x & 0x0f;  
        out += hex[i];  
    }  
    return out;  
}  

function hex2int(hex) {  
    var len = hex.length,  
        a = new Array(len),  
        code;  
    for (var i = 0; i < len; i++) {  
        code = hex.charCodeAt(i);  
        if (48 <= code && code < 58) {  
            code -= 48;  
        } else {  
            code = (code & 0xdf) - 65 + 10;  
        }  
        a[i] = code;  
    }  
    return a.reduce(function(acc, c) {  
        acc = 16 * acc + c;  
        return acc;  
    }, 0);  
}  

function prefixInteger(num, n) {  
    return (Array(n).join(0) + num).slice(-n);  
}  

function reverseTwo(str) {  

    var str1 = "";  
    for (var i = 1; i <= str.length; i++) {  
        str1 += str[i - 1];  
        if (i % 2 == 0) {  
            if (i == str.length) {  
                break;  
            }  
            str1 += ":";  
        }  
    }  
    var str2 = "";  
    for (var i = str1.split(":").length - 1; i >= 0; i--) {  
        str2 += str1.split(":")[i];  
    }  
    return str2;  
}  

if (uni.getSystemInfoSync().platform == 'android') {  
    //plus.globalEvent.addEventListener('plusready', listenNFCStatus, false);  
}  

function writeData() {  
    var textEle = plus.globalEvent.getElementById('text');  
    if (!textEle.value) {  
        uni.showToast({  
            title: '请输入要写入的内容!',  
            icon: 'none'  
        });  
        return;  
    }  
    readyWriteData = true;  
    waiting = plus.nativeUI.showWaiting("请将NFC标签靠近!");  
}  

function readData(getCardNo) {  
    readyRead = true;  
    _getCardNo = getCardNo  
    waiting = plus.nativeUI.showWaiting("请将NFC标签靠近!", {  
        modal: false  
    });  
}  

function closeReadAndWrite() {  
    readyWriteData = false;  
    readyRead = false;  

    if (waiting) {  
        waiting.close();  
    }  
}
2023-04-22 23:44 负责人:无 分享
已邀请:
7***@qq.com

7***@qq.com

解决了吗?

套马杆的套子

套马杆的套子 - 没有解决不了的问题,只有解决不完的问题

我这有一个安卓的nfc读取代码,你可以试试可以不,附件是nfc.js,下面代码是如何使用

<uni-popup ref="alertDialog" type="dialog">  
                <uni-popup-dialog type="info" title="提示" content="请将手机靠近NFC贴,直到震动" :isShowCfirm="isShowCfirm">  
                </uni-popup-dialog>  
            </uni-popup>  

that.nfc.NFCInit(that, 'alertDialog')  

plus.globalEvent.addEventListener("resume", function(e) {  

                                    var code = that.nfc.NFCReadUID()  
                                    that.$refs.alertDialog.close()  
                                    if (code != null && code != '') {  
                                        // console.log('1111111',code,that.selectItem.id,type)  

                                    } else {  
                                        that.$toast('NFC内容为空!')  
                                    }  

                                }, false);  
  • 7***@qq.com

    现在是鸿蒙系统的手机是可以的,安卓手机不行。打开的是系统默认的应用

    2024-07-17 10:50

7***@qq.com

7***@qq.com

解决了,在https://ask.dcloud.net.cn/article/id-40677__page-2#reply这里找到了解决方法。

如果是鸿蒙手机的话 需要添加 设置为

if (parseInt(new IntentFilter("android.os.Build.VERSION.SDK_INT").UUID) >= parseInt(new IntentFilter("android.os.Build.VERSION_CODES.S").UUID)) {

var pendingIntent = PendingIntent.getActivity(ESUtils.NFC.mainNFC, 0, _intent, PendingIntent.FLAG_IMMUTABLE);

} else {

var pendingIntent = PendingIntent.getActivity(ESUtils.NFC.mainNFC, 0, _intent, PendingIntent.FLAG_MUTABLE);

}

要回复问题请先登录注册