vue app混合開發藍牙串口連接(報錯java.io.IOException: read failed, socket might closed or timeout, read ret: -1;at android.bluetooth.BluetoothSocket.connect at js/BluetoothTool.js:329)


我使用的uni-app
<template>
    <view class="bluetooth">
        <!-- 發送數據 -->
        <view class="send" v-if="send_data_onoff">
            <view class="uni-textarea">
                <textarea placeholder-style="color:#F76260" v-model="send_data_list" placeholder="請輸入發送數據"/>
                <view @tap="send_data" class="fasong">發送</view>
            </view>
        </view>
        <!-- 沒有匹配的藍牙設備 -->
        <view class="no_match_bluetooth_list" v-if="no_match_list.length!=0">
            <view class="h1">已搜索的藍牙:</view>
            <block  v-for="(item,index) in no_match_list" :key="index">
                <view class="uni-list" @tap="search_bluetooth(item.SN)">
                    <view class="uni-list-cell" hover-class="uni-list-cell-hover">
                        <view class="uni-list-cell-navigate uni-navigate-right uni-media-list ">
                            <view class="uni-media-list-body">
                                <view>藍牙名稱:{{item.name}}</view>
                                <view>SN:{{item.SN}}</view>
                            </view>
                        </view>
                    </view>
                </view>
            </block>
        </view>
        
        <!-- 已匹配的藍牙設備 -->
        <view class="no_match_bluetooth_list" v-if="match_list.length!=0">
            <view class="h1">已匹配的藍牙:</view>
            <block  v-for="(item,index) in match_list" :key="index">
                <view class="uni-list" @tap="print(item.SN)">
                    <view class="uni-list-cell" hover-class="uni-list-cell-hover">
                        <view class="uni-list-cell-navigate uni-navigate-right uni-media-list ">
                            <view class="uni-media-list-body">
                                <view>藍牙名稱:{{item.name}}</view>
                                <view>SN:{{item.SN}}</view>
                            </view>
                        </view>
                    </view>
                </view>
            </block>
        </view>
        
        
        
        <view class="btn">
            <view class="btn_1" @tap="open_bluetooth">打開藍牙</view>
            <view class="btn_2" @tap="close_bluetooth">關閉藍牙</view>
            <view class="btn_3" @tap="search_bluetooth">搜索藍牙</view>
        </view>
    </view>
</template>

<script>
    var main, Context, BluetoothManager, BluetoothAdapter, BManager, BAdapter,BluetoothDevice,IntentFilter,bluetoothSocket,device;
    export default {
        data() {
            return {
                bArray:[],//用於搜索藍牙去重用的
                no_match_list:[],//沒有配對的藍牙列表
                match_list:[],//已配對的藍牙列表
                send_data_onoff:false,
                send_data_list:'',//要發送的數據
            };
        },
        onShow() {
            //獲取android應用Activity對象
            main = plus.android.runtimeMainActivity();
            Context = plus.android.importClass("android.content.Context");
            BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
            //藍牙適配器
            BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
            //藍牙本地適配器
            BAdapter = BluetoothAdapter.getDefaultAdapter();
            //藍牙設備
            BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice');
            //過濾器
            IntentFilter = plus.android.importClass('android.content.IntentFilter');
        },
        methods:{
            /**
            * 根據藍牙地址,連接設備
            * @param {Object} address
            * @return {Boolean}
            */
            print(address){
                console.log(address)
                let that=this
                uni.showModal({
                    title: '提示',
                    content: '是連接此藍牙?',
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用戶點擊確定');
                            uni.showLoading({
                                title: '藍牙連接中...'
                            });
                            that.print_bluetooth(address)
                            
                        }
                    }
                });
            },
            //連接藍牙
            print_bluetooth(mac_address){
                let that=this
                uni.hideLoading()
                let UUID = plus.android.importClass("java.util.UUID");
                let uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                device = BAdapter.getRemoteDevice(mac_address);
                plus.android.importClass(device);
                bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                plus.android.importClass(bluetoothSocket);
                if (!bluetoothSocket.isConnected()) {
                    console.log('檢測到設備未連接,嘗試連接....');
                    bluetoothSocket.connect();
                }
                console.log('設備已連接');
                // 打開輸入發送數據
                that.send_data_onoff=true;
                
            },
            //發送藍牙數據
            send_data(){
                let that=this
                console.log()
                if (bluetoothSocket.isConnected()) {
                    console.log(22222)
                    var outputStream = bluetoothSocket.getOutputStream();
                    plus.android.importClass(outputStream);
                    var string = that.send_data_list
                    var bytes = plus.android.invoke(string, 'getBytes', 'gbk');//創建輸出流失敗
                    outputStream.write(bytes);
//                     outputStream.flush();
//                     device = null //這里關鍵
//                     bluetoothSocket.close(); //必須關閉藍牙連接否則意外斷開的話打印錯誤
                }
            },
            open_bluetooth(){
                if(!BAdapter.isEnabled()) {
                    BAdapter.enable();//啟動藍牙
                    uni.showToast({
                        title: '藍牙已啟動',
                        duration: 2000
                    })    
                }
            },
            //關閉藍牙
            close_bluetooth(){
                let that =this
                //關閉藍牙都把之前的清空
                that.no_match_list=[];
                that.match_list=[]
                if (BAdapter.isEnabled()) {
                    BAdapter.disable();//關閉藍牙
                    uni.showToast({
                        title: '藍牙已關閉',
                        duration: 2000
                    })
                }
            },
            //獲取已匹配藍牙設備
            bluetooth_list(){
                let that=this
                //先清空
                that.match_list=[]
                
                var lists = BAdapter.getBondedDevices();
                plus.android.importClass(lists);
                var iterator = lists.iterator();
                plus.android.importClass(iterator);
                while (iterator.hasNext()) {
                    var d = iterator.next();
                    plus.android.importClass(d);
                    let arr={
                        "name": d.getName(),
                        "SN": d.getAddress()
                    }
                    that.match_list.push(arr)
                }
            },
            //搜索沒匹配的藍牙設備
            search_bluetooth(address){
                let that=this
                //判斷藍牙是否開啟
                if (!BAdapter.isEnabled()) {
                    uni.showToast({
                        title: '請先打開藍牙',
                        duration: 3000
                    });
                    return
                }
                if(address.length!=undefined){
                    uni.showModal({
                        title: '提示',
                        content: '是否配對此藍牙?',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用戶點擊確定');
                                uni.showLoading({
                                    title: '藍牙匹配中...'
                                });
                                that.search_pipei(address)
                            }
                        }
                    });
                }else{
                    uni.showLoading({
                        title: '藍牙搜索中...'
                    });
                    that.search_pipei()
                }
            },
            //搜索和匹配藍牙
            search_pipei(address){
                let that=this
                //獲取已匹配的藍牙
                that.bluetooth_list()
                //每次搜索都把之前的清空
                that.bArray=[];
                that.no_match_list=[];
                
                var filter = new IntentFilter();
                var BDevice = new BluetoothDevice();
                BAdapter.startDiscovery(); //開啟搜索
                var receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
                    onReceive: function(context, intent) { //回調
                        try {               
                            plus.android.importClass(intent); //通過intent實例引入intent類
                            if(intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
                                uni.hideLoading()
                                main.unregisterReceiver(receiver); //取消監聽 
                            } else {
                                //從Intent中獲取設備對象
                                BDevice= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                //配對藍牙
                                if (address == BDevice.getAddress()) {
                                    if (BDevice.createBond()) { //配對命令.createBond()
                                        console.log("配對成功");
                                        uni.hideLoading()
                                    }
                
                                }
                                if(BDevice == null) {
                                    main.unregisterReceiver(receiver); //取消監聽
                                    uni.hideLoading()
                                    //獲取已匹配的藍牙
                                    that.bluetooth_list()
                                    return;
                                }
                                var name=BDevice.getAddress()+BDevice.getName();
                                if(that.bArray.indexOf(name) == -1){     //去重
                                    that.bArray.push(name);//用於去重的
                                    let arr={
                                        "name": BDevice.getName(),
                                        "SN": BDevice.getAddress()
                                    }
                                    that.no_match_list.push(arr)
                                    console.log(JSON.stringify(that.no_match_list))
                                }

                            }
                        } catch(e) {
                            console.error(e);
                        }
                    }
                });
                filter.addAction(BDevice.ACTION_FOUND);
                filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
                filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
                filter.addAction(BAdapter.ACTION_STATE_CHANGED);
                main.registerReceiver(receiver, filter); //注冊監聽 
            },
        }
    }
</script>

<style scoped="scoped" lang="scss">
@import "./Bluetooth.scss";
</style>

css

.bluetooth{
    padding: 20upx 20upx 120upx;
    .h1{
        padding: 20upx 0;color: #1482D1;border-top: 1upx solid #EFEFF4;
    }
    
    .btn{
        display:flex;position:fixed;bottom:0upx;padding:20upx 10upx;justify-content:space-around;width: 100%;color:#fff;border-top:1px solid #f2f2f2;background-color: #fff;
        view{
            width: 200upx;height: 80upx;line-height:80upx;text-align: center;border-radius:10upx;
        }
        .btn_1{
            background-color: #009BDE;
        }
        .btn_2{
            background-color: red;
        }
        .btn_3{
            background-color: #3CB371;
        }
    }
    .uni-textarea{
        textarea{
            border: 1px solid #EFEFF4;border-radius: 10px;width: 100%;padding: 10upx;box-sizing: border-box;
        }
        .fasong{
            width: 100%;padding:15upx 10upx;box-sizing: border-box;border-radius: 10px;background: #1482D1;text-align: center;color: white;margin: 10px 0;
        }
    }
}

如果報錯你可能需要下載一個藍牙開發助手當服務端


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM