0

当第一个选择为“DISCOVERER”而另一个选择为“CONNECTOR”时,我在这里编写的代码似乎连接了两个设备。
当我尝试执行“SEND PACKAGE”时,它说 Payload 已发送,但另一台设备完全没有执行任何操作。

对于这个项目,我使用
https://pub.dev/packages/nearby_connections (3.1.0)
https://pub.dev/packages/permission_handler (8.3.0)
点对点策略,在这个情况下,是 P2P_CLUSTER。(可以在这里找到不同的策略 https://developers.google.com/nearby/connections/strategies

idFriend 在开始时为 0。稍后它将在每个设备上将其覆盖为每个设备上的 EndPointId。
作为连接器的设备的用户名
是 2。作为发现者的设备的用户名是 1。


另外,我在下面添加了代码,例如 acceptpackage() 和 sendpack()。sendpack() 似乎有效,而 acceptpackage() 实际上并不接受它,特别是因为 acceptpackage() 已经在 connect() 的代码中。
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:nearby_connections/nearby_connections.dart';
import 'package:permission_handler/permission_handler.dart';

final String connector_userName = "2";
final String discoverer_userName = "1";
final Strategy strategy = Strategy.P2P_CLUSTER;

class peerwidget extends StatefulWidget {
  @override
  _peerwidgetState createState() => _peerwidgetState();
}

String mytext = "";

class _peerwidgetState extends State<peerwidget> {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text("Somecrab", textDirection: TextDirection.ltr),
          actions: <Widget>[
            IconButton(
                icon: const Icon(Icons.settings),
                onPressed: () {
                  print("OPENING SETTINGS FOR BACKGROUND COLOR AND SUCH");
                }),
          ]),
      body: SingleChildScrollView(
        child: Column(children: <Widget>[
          Container(
            child: Text(mytext),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("location");
              //setstate oderso, nächsts Bild holle
              locationpermission();
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("Ask location"),
              ],
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("storage");
              //setstate oderso, nächsts Bild holle
              storagepermission();
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("Ask storage"),
              ],
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("Kill all");
              //setstate oderso, nächsts Bild holle
              closeall();
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("Kill all"),
              ],
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("CONNECT");
              //setstate oderso, nächsts Bild holle

              setState(() {
                connect();
              });
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("CONNECT"),
              ],
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("DISCOVER");
              //setstate oderso, nächsts Bild holle
              setState(() {
                discover();
              });
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("DISCOVER"),
              ],
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("SEND PACKAGE");
              //setstate oderso, nächsts Bild holle
              setState(() {
                sendpack();
              });
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("SEND PACKAGE"),
              ],
            ),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              minimumSize: const Size(140, 50),
            ),
            onPressed: () {
              print("ACCEPT PACKAGE");
              //setstate oderso, nächsts Bild holle
              setState(() {
                acceptpackage();
              });
            },
            child: Column(
              // Replace with a Row for horizontal icon + text
              children: const <Widget>[
                Icon(Icons.arrow_forward),
                Text("ACCEPT PACKAGE"),
              ],
            ),
          ),
        ]),
      ),
    );
  }
}

onConnectionInitiated() {
  mytext = "onConnectionInitiated";
}

onConnectionResult() {
  mytext = "onConnectionResult";
}

onDisconnected() {
  mytext = "onConnectionDisconnected";
}

onEndpointFound(String id, String username, String serviceId) {
  mytext = "Found: " + id + username + serviceId;
}

onEndpointLost() {
  mytext = "onEndpointLost";
}

bool connectionexists = false;
//var theendpointid = "1";
String idFriend = "0";
connect() async {
  print("connecting started...");
  mytext = "connection started";
  try {
    await Nearby().startAdvertising(
      connector_userName,
      strategy,
      onConnectionInitiated: (String id, ConnectionInfo info) {
        print("[CONNECTION INITIATED]: \n ID: " +
            id +
            " info: " +
            info.toString());
        idFriend = id;

        Nearby().acceptConnection(id, onPayLoadRecieved: (endpointId, payload) {
          print("[ACCEPT CONNECTION]: \n EndpointID: " +
              endpointId +
              " Payload: " +
              payload.toString());
          // called whenever a payload is recieved.
        }, onPayloadTransferUpdate: (endpointId, payloadTransferUpdate) {
          print("[PAYLOAD TRANSFER UPDATE]: \n endpointId: " +
              endpointId +
              " PayloadTransferUpdate: " +
              payloadTransferUpdate.toString());
          // gives status of a payload
          // e.g success/failure/in_progress
          // bytes transferred and total bytes etc
        });
      },
      onConnectionResult: (String id, Status status) {
        print("[CONNECTION RESULT] \n ID: " +
            id +
            " status: " +
            status.toString());
        // Called when connection is accepted/rejected
      },
      onDisconnected: (String id) {
        print("[DISCONNECTED] \n ID: " + id);
        // Callled whenever a discoverer disconnects from advertiser
        onDisconnected();
      },
      serviceId: "com.simon.fluttershit", // uniquely identifies your app
    );
  } catch (PlatformException) {
    print("exception at 187");
    print("insufficient permissions or some error!");
    // platform exceptions like unable to start bluetooth or insufficient permissions
  }
}

discover() async {
  //print("the connection existance is:" + connectionexists.toString());
  mytext = "discovery started";
  //Does it stay within this loop because await? No.

  /*if (connectionexists == false) {*/
  try {
    await Nearby().startDiscovery(
      discoverer_userName,
      strategy,
      onEndpointFound: (String id, String userName, String serviceId) {
        print("[ENDPOINT FOUND]: \n ID: " +
            id +
            " userName: " +
            userName +
            " serviceId: " +
            serviceId +
            "\n");
        print("WAS CONNECTED TO: " + discoverer_userName);

        try {
          Nearby().requestConnection(
            userName,
            id,
            onConnectionInitiated: (id, info) {
              print("[CONNECTION INITIATED]: \n ID: " +
                  id +
                  " Info: " +
                  info.toString());
              connectionexists = true;
              idFriend = id;
            },
            onConnectionResult: (id, status) {
              print("[CONNECTION RESULT]: \n" + id + " " + status.toString());
            },
            onDisconnected: (id) {
              print("[DISCONNECTED]: \n" + id);
              connectionexists = false;
            },
          );
        } catch (PlatformException) {
          print("exception at 187");
          print("insufficient permissions or some error!");
        }
      },
      serviceId: "com.simon.fluttershit",
      onEndpointLost: (String? endpointId) {
        print("[ENDPOINT LOST]: \n" + endpointId.toString());
      }, // uniquely identifies your app
    );
  } catch (PlatformException) {
    print("exception at 187");
    print("insufficient permissions or some error!");
    // platform exceptions like unable to start bluetooth or insufficient permissions
  }
  /*} else {
    print("please disconnect first!");
  }*/
}

void sendpack() {
  List<int> data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0];
  Uint8List bytes = Uint8List.fromList(data);
  Nearby().sendBytesPayload(idFriend, bytes);
  print("[SENDPACK]: Receiver ID: " +
      idFriend.toString() +
      "Data: " +
      bytes.toString());
}

void acceptpackage() {
  Nearby().acceptConnection(idFriend, onPayLoadRecieved: (endpointId, payload) {
    print("Something was received: EndpointId: " +
        endpointId +
        " Payload: " +
        payload.toString());
    // called whenever a payload is recieved.
  }, onPayloadTransferUpdate: (endpointId, payloadTransferUpdate) {
    print("The status of Payload is: EndPointId: " +
        endpointId +
        " PayloadTransferUpdate: " +
        payloadTransferUpdate.toString());
    // gives status of a payload
    // e.g success/failure/in_progress
    // bytes transferred and total bytes etc
  });
}

void locationpermission() {
  Nearby().askLocationPermission();
}

void storagepermission() {
  Nearby().askExternalStoragePermission();
}

void closeall() {
  connectionexists = false;
  Nearby().stopAdvertising();
  Nearby().stopDiscovery();
  Nearby().stopAllEndpoints();
}

发送到发现者的有效负载连接器上的输出:

I/flutter (28055): [CONNECTION INITIATED]: 
I/flutter (28055):  ID: D0ND info: Instance of 'ConnectionInfo'
I/ViewRootImpl@d507b48[MainActivity](28055): ViewPostIme pointer 0
I/ViewRootImpl@d507b48[MainActivity](28055): ViewPostIme pointer 1
I/flutter (28055): SEND PACKAGE
D/nearby_connections(28055): sentPayload
I/flutter (28055): [SENDPACK]: Receiver ID: D0NDData: [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]
D/nearby_connections(28055): ad.onConnectionResult

发现者向连接器发送有效负载的输出:

I/flutter (28055): connecting started...
D/nearby_connections(28055): startAdvertising
D/nearby_connections(28055): ad.onConnectionInitiated
I/flutter (28055): [CONNECTION INITIATED]: 
I/flutter (28055):  ID: M9N3 info: Instance of 'ConnectionInfo'
I/ViewRootImpl@d507b48[MainActivity](28055): ViewPostIme pointer 0
I/ViewRootImpl@d507b48[MainActivity](28055): ViewPostIme pointer 1
I/flutter (28055): ACCEPT PACKAGE
E/flutter (28055): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(Failure, 8009: STATUS_OUT_OF_ORDER_API_CALL, null, null)
E/flutter (28055): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (28055): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (28055): <asynchronous suspension>
E/flutter (28055): #2      Nearby.acceptConnection (package:nearby_connections/src/nearby.dart:342:12)
E/flutter (28055): <asynchronous suspension>
E/flutter (28055): 

该程序的图片,用于发现者和连接器: 我的应用程序的屏幕截图

请帮我弄清楚为什么发现者或连接器都没有收到 PayLoad。

4

0 回答 0