串口蓝牙(SPP)服务端链接

前言

前面说了客户端主动连接,这里面说下服务端如何简单吧
其实和java的socket监听基本一模一样,就是端口换成了uuid而已

创建监听

通过

mBluetooth = BluetoothAdapter.getDefaultAdapter();

获取mBluetooth蓝牙对象
然后调用listenUsingInsecureRfcommWithServiceRecord方法就可以,这方法有两个参数,分别是name和uuid
name就是一个命名,你自己起一个就行
uuid就等同java socket服务里面的端口

BluetoothServerSocket bluetoothService = mBluetooth.listenUsingInsecureRfcommWithServiceRecord("bluetoothSPP", UUID.fromString(BluetoothObject.SPP_UUID));
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    while (true){
    
    
                        BluetoothSocket accept = bluetoothService.accept();
                        BluetoothServiceConnect bluetoothServiceConnect = new BluetoothServiceConnect();
                        bluetoothServiceConnect.start(mcontex, accept,BluetoothObject.SPP_UUID);
                        Intent liaoTian = new Intent(mcontex, Liao_tian.class);
                        BluetoothDevice bluetoothDevice = accept.getRemoteDevice();
                        String name = bluetoothDevice.getName();
                        if(name == null || name.length()==0){
    
    
                            name=  bluetoothDevice.getAddress();
                        }
                        liaoTian.putExtra("bluetoothName",name);
                        liaoTian.putExtra("bluetoothAdd",bluetoothDevice.getAddress());
                        liaoTian.putExtra("bluetoothUUid",BluetoothObject.SPP_UUID);
                        mcontex.startActivity(liaoTian);
                    }
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }).start();
    }

这里注意下
bluetoothService.accept()这个方法是阻塞方法
如果有蓝牙连接过来,就会获取socket对象,然后你就可以获取输入输出流了
我这里面就是如果有蓝牙连接过来,跳到其他页面

猜你喜欢

转载自blog.csdn.net/qq_39164154/article/details/127793357
今日推荐