0

我正在尝试在 Android 平台上使用蓝牙连接到设备。在这里,我使用了一个名为 flutter Bluetooth serial 的插件进行蓝牙连接。有了这个插件,我可以连接到蓝牙设备,如扬声器、耳机。但是,当我尝试连接到手机/笔记本电脑时,它会给我错误平台异常。我该如何解决这个问题,请您帮帮我。下面是我正在使用的蓝牙连接的示例代码。

    ```class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: BluetoothApp(),
        );
      }
    }
    
    class BluetoothApp extends StatefulWidget {
      @override
      _BluetoothAppState createState() => _BluetoothAppState();
    }
    
    class _BluetoothAppState extends State<BluetoothApp> {
      var sender;
      var dataLength;
      **Initializing the Bluetooth connection state to be unknown**
      BluetoothState _bluetoothState = BluetoothState.UNKNOWN;
      **Get the instance of the Bluetooth**
      FlutterBluetoothSerial bluetoothSerial = FlutterBluetoothSerial.instance;
    
      **Track the Bluetooth connection with the remote device**
      BluetoothConnection? connection;
    
      int deviceState = 0;
    
      bool isDisconnecting = false;
    
      **To track whether the device is still connected to Bluetooth**
      bool get isConnected => connection != null && connection!.isConnected;
    
      List<BluetoothDevice> devices = List.empty(growable: true); **For getting list of Bluetooth device which are enabled **
      BluetoothDevice? device;
      bool connected = false;
      bool _isButtonUnavailable = false;
    
      bool enabled = false;
    
      @override
      void initState() {
        super.initState();
        deviceState = 0;
        // Listen for further state changes
        FlutterBluetoothSerial.instance
            .onStateChanged()
            .listen((BluetoothState state) {
          setState(() {
            _bluetoothState = state;
            if (_bluetoothState == BluetoothState.STATE_OFF) {
              _isButtonUnavailable = true;
            }
            searchForBluetoothDevices(); **This Method is used to Discover the Bluetooth devices**
          });
        });
        enableBluetooth(); **This Method is used for asking Bluetooth permission** 
      }
    
      @override
      void dispose() {
        // Avoid memory leak and disconnect
        if (isConnected) {
          isDisconnecting = true;
          connection!.dispose();
          connection = null;
        }
    
        super.dispose();
      }
    
      ** Request Bluetooth permission from the user**
      Future<bool> enableBluetooth() async {
        ** Retrieving the current Bluetooth state**
        _bluetoothState = await FlutterBluetoothSerial.instance.state;
    
        ** If the bluetooth is off, then turn it on first**
        ** and then retrieve the devices that are Discovered.**
        if (_bluetoothState == BluetoothState.STATE_OFF) {
          enabled = (await FlutterBluetoothSerial.instance.requestEnable())!;
          if (enabled == true) {
            searchForBluetoothDevices();
          } else {}
    
          return true;
        } else {
          searchForBluetoothDevices();
        }
        return false;
      }
    
      void searchForBluetoothDevices() {
        try {
          bluetoothSerial.startDiscovery().listen((result) {
            setState(() {
              devices.add(result.device); **Used to add devices to List after Discovered**
            });
          }).onDone(() {
            print("Discovery Stopped");
            connected = false;
          });
        } on PlatformException {
          print("Error");
        }
    
        ** It is an error to call [setState] unless [mounted] is true.**
        if (!mounted) {
          return;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            key: _scaffoldKey,
            appBar: AppBar(
              title: Text("Flutter Bluetooth"),
            ),
            body: Container(
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  ListView(
                    shrinkWrap: true,
                    children: devices
                        .map((e) => ListTile(
                              title: Text(e.name ?? ''),
                              trailing: ElevatedButton(
                                onPressed: () => _isButtonUnavailable
                                    ? null
                                    : connected
                                        ? disconnect()**Used to Disconnect the device**
                                        : connect(e.address), **Used to connect the Device by sending the Bluetooth address to this method**
                                child: Text(connected ? 'Disconnect' : 'Connect'),
                              ),
                            ))
                        .toList(),
                  ),
                ],
              ),
            ),
            /*  floatingActionButton: FloatingActionButton(
          
            onPressed: () => enableBluetooth(),
           
           
            child: Icon(Icons.find_replace),
          ),  */
          ),
        );
      }
    
      ** Method to connect to bluetooth**
      void connect(String deviceAddress) async {
        setState(() {
          _isButtonUnavailable = true;
        });
    
       
        if (deviceAddress == null) {
          show('No device selected');
        } else {
          if (!isConnected) {
            await BluetoothConnection.toAddress(deviceAddress).then((_connection)***Plateform Exception*** {
              print('Connected to the device');
              connection = _connection;
              
              setState(() {
                connected = true;
              });
    
              connection!.input!.listen(null).onDone(() {
                if (isDisconnecting) {
                  print('Disconnecting locally!');
                } else {
                  print('Disconnected remotely!');
                }
                if (this.mounted) {
                  setState(() {});
                }
              });
            }).catchError((error) {
              print('Cannot connect, exception occurred');
              print(error);
            });
    
            setState(() => _isButtonUnavailable = false);
          }
        }
      }
    
      ** Method to disconnect bluetooth**
      void disconnect() async {
        setState(() {
          _isButtonUnavailable = true;
          deviceState = 0;
        });
    
        await connection!.close();
        show('Device disconnected');
        if (connection!.isConnected) {
          setState(() {
            connected = false;
            _isButtonUnavailable = false;
          });
        }
      }```

  

<PlatformException (PlatformException(connect_error, read failed, socket might closed or timeout, read ret: -1, java.io.IOException: read failed, socket might closed or timeout, read ret: -1
        at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:940)
        at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:954)
        at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:502)
        at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:57)
        at io.github.edufolly.flutterbluetoothserial.BluetoothConnection.connect(BluetoothConnection.java:64)
        at io.github.edufolly.flutterbluetoothserial.FlutterBluetoothSerialPlugin.lambda$onMethodCall$0$FlutterBluetoothSerialPlugin(FlutterBluetoothSerialPlugin.java:880)
        at io.github.edufolly.flutterbluetoothserial.-$$Lambda$FlutterBluetoothSerialPlugin$IghJwXXwUz_TFyaj49DgLpHhUY4.run(Unknown Source:10)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
    , null))
<Is their any other Plugin to use for bluetooth connection except flutter_bluetooth_serial.
4

0 回答 0