huawei_nearbyservice 5.0.4+302
huawei_nearbyservice: ^5.0.4+302 copied to clipboard

Flutter Android

Nearby Service Data Communication allows apps to easily discover nearby devices and set up communication with them using technologies such as Bluetooth and Wi-Fi.

Huawei Nearby Service Flutter Plugin #


Contents #


1. Introduction #

Nearby Data Communication allows devices to easily discover nearby devices and set up communication with them using technologies such as Bluetooth and Wi-Fi. The plugin provides Nearby Connection, Nearby Message, and Nearby Wi-Fi Sharing APIs provided by the HUAWEI Nearby Service SDK.

  • Nearby Connection

    Discovers devices and sets up secure communication channels with them without connecting to the Internet and transfers byte arrays, files, and streams to them; supports seamless nearby interactions, such as multi-player gaming, real-time collaboration, resource broadcasting, and content sharing.

  • Nearby Message

    Allows message publishing and subscription between nearby devices that are connected to the Internet. A subscriber (app) can obtain the message content from the cloud service based on the sharing code broadcast by a publisher (beacon or another app).

  • Nearby Wi-Fi Sharing

    Provides the Wi-Fi configuration sharing function to help users connect their own or friends' smart devices to the Wi-Fi network in one-click mode.

2. Installation Guide #

Before you get started, you must register as a HUAWEI Developer and complete identity verification on the HUAWEI Developers. For details, please refer to Register a HUAWEI ID.

Creating a Project in AppGallery Connect #

Creating an app in the AppGallery Connect is required in order to communicate with the Huawei services. To create an app, perform the following steps:

Step 1. Sign in to AppGallery Connect and select My projects.

Step 2. Select your project from the project list or create a new one by clicking the Add Project button.

Step 3. Go to Project Setting > General information, and click Add app. If an app exists in the project and you need to add a new one, expand the app selection area on the top of the page and click Add app.

Step 4. On the Add app page, enter the app information, and click OK.

Configuring the Signing Certificate Fingerprint #

A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core (APK) through the HMS SDK. Before using the HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in the AppGallery Connect. You can refer to 3rd and 4th steps of Generating a Signing Certificate codelab tutorial for the certificate generation. Perform the following steps after you have generated the certificate.

Step 1: Sign in to AppGallery Connect and select your project from My Projects. Then go to Project Setting > General information. In the App information field, click the add icon next to SHA-256 certificate fingerprint, and enter the obtained SHA-256 certificate fingerprint.

Step 2: After completing the configuration, click OK (Check mark icon) to save the changes.

Integrating the Flutter Nearby Service Plugin #

Step 1: Sign in to AppGallery Connect and select your project from My Projects. Then go to Project Settings > Manage APIs and make sure the Nearby Service is enabled.

Step 2: Go to Project Setting > General information page, under the App information field, click agconnect-services.json to download the configuration file.

Step 3: Copy the agconnect-services.json file to the android/app directory of your project.

Step 4: Open the build.gradle file in the android directory of your project.

  • Navigate to the buildscript section and configure the Maven repository address and agconnect plugin for the HMS SDK.

    buildscript {
      repositories {
          google()
          jcenter()
          maven { url 'https://developer.huawei.com/repo/' }
      }
    
      dependencies {
          /* 
          * <Other dependencies>
          */
          classpath 'com.huawei.agconnect:agcp:1.4.2.301'
      }
    }
    
    • Go to allprojects and configure the Maven repository address for the HMS SDK.
    allprojects {
      repositories {
          google()
          jcenter()
          maven { url 'https://developer.huawei.com/repo/' }
      }
    }
    

    Step 5: Open the build.gradle file in the android/app/ directory.

  • Add apply plugin: 'com.huawei.agconnect' line after other apply entries.

    apply plugin: 'com.android.application'
    apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
    apply plugin: 'com.huawei.agconnect'
    
  • Set your package name in defaultConfig > applicationId and set minSdkVersion to 21 or higher. Package name must match with the package_name entry in the agconnect-services.json file.

    defaultConfig {
        applicationId "<package_name>"
        minSdkVersion 21
        /*
        * <Other configurations>
        */
    }
    

    Step 6: Configure the signature in android according to the signature file information.

          android {
              /*
               * <Other configurations>
               */
    
              signingConfigs {
                  config {
                      storeFile file('<keystore_file>')
                      storePassword '<keystore_password>'
                      keyAlias '<key_alias>'
                      keyPassword '<key_password>'
                  }
              }
    
              buildTypes {
                  debug {
                      signingConfig signingConfigs.config
                  }
                  release {
                      /*
                      * <Other configurations>
                      */
                      signingConfig signingConfigs.config
                  }
              }
          }
    

    Step 7: On your Flutter project directory, find and open your pubspec.yaml file and add the huawei_nearbyservice library to dependencies. For more details please refer to the Using packages document.

    • To download the package from pub.dev.

        dependencies:
          huawei_nearbyservice: {library version}
      

      or

      If you downloaded the package from the HUAWEI Developers, specify the library path on your local device.

        dependencies:
          huawei_nearbyservice:
              # Replace {library path} with actual library path of Huawei Nearby Service Plugin for Flutter.
              path: {library path}
      
      • Replace {library path} with the actual library path of the Flutter Nearby Service Plugin. The following are examples:
        • Relative path example: path: ../huawei_nearbyservice
        • Absolute path example: path: D:\Projects\Libraries\huawei_nearbyservice
**Step 8:** Run the following command to update the package info.
```
[project_path]> flutter pub get
```

**Step 9:** Import the library to access the methods.

```dart
import 'package:huawei_nearbyservice/huawei_nearbyservice.dart';
```

**Step 10:** Run the following command to start the app.

```
[project_path]> flutter run
```

3. API Reference #

HMSNearby #

The plugin class which provides some general methods.

Method Summary

MethodReturn TypeDescription
getVersionFuture<String>Obtains the Nearby Service SDK version number.
equalsMessageFuture<bool>Checks whether two Messages are equal on the platform side.
enableLoggerFuture<void>Enables HMS Plugin Method Analytics.
disableLoggerFuture<void>Disables HMS Plugin Method Analytics.

Methods

static Future<String> getVersion()

Obtains the Nearby Service SDK version number.

Return Type
TypeDescription
Future<String>Nearby Service SDK version number.
Call Example
String version = await HMSNearby.getVersion();
static Future<bool> equalsMessage(Message object, Message other)

Checks whether two Messages are equal on the platform side.

Parameters
ParameterTypeDescription
objectMessageMessage to be compared.
otherMessageMessage to be compared.
Return Type
TypeDescription
Future<bool>Whether the messages are equal.
Call Example
msg = Message(content: utf8.encode("Hello there!"));
msg2 = Message(content: utf8.encode("Hello back!"));
bool equals = HMSNearby.equalsMessage(msg, msg2);
static Future<void> enableLogger()

Enables HMS Plugin Method Analytics which is used for sending usage analytics of Nearby Service SDK's methods to improve the service quality.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
HMSNearby.enableLogger();
static Future<void> disableLogger()

Disables HMS Plugin Method Analytics which is used for sending usage analytics of Nearby Service SDK's methods to improve the service quality.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
HMSNearby.disableLogger();

HMSNearbyApiContext #

Provides APIs for setting and obtaining API credentials.

Method Summary

MethodReturn TypeDescription
instanceHMSNearbyApiContextObtains the singleton instance of the class.
setApiKeyFuture<void>Sets the API credential for your app.
getApiKeyFuture<void>Obtains the current API credential.

Methods

static HMSNearbyApiContext get instance

Obtains the singleton instance of the class.

Return Type
TypeDescription
HMSNearbyApiContextSingleton instance of the class.
Call Example
instance = HMSNearbyApiContext.instance;
Future<void> setApiKey(String apiKey) async

Sets the API credential for your app.

Parameters
ParameterTypeDescription
apiKeyStringAPI Credential.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await HMSNearbyApiContext.instance.setApiKey('sample-api-key');
Future<String> getApiKey() async

Obtains the current API credential.

Return Type
TypeDescription
Future<String>Current API credential.
Call Example
String apiKey = await HMSNearbyApiContext.instance.getApiKey();

Discovery Engine #

This section contains the classes related to the Discovery Engine.

HMSDiscoveryEngine #

An entry class for broadcasting, scanning, and connection. This class implements related methods for these features.

Method Summary

MethodReturn TypeDescription
instanceHMSDiscoveryEngineObtains the singleton instance of the class.
acceptConnectFuture<void>Accepts a connection.
disconnectFuture<void>Disconnects from a remote endpoint.
rejectConnectFuture<void>Rejects a connection request from a remote endpoint.
requestConnectFuture<void>Sends a request to connect to a remote endpoint.
startBroadcastingFuture<void>Starts broadcasting.
startScanFuture<void>Starts to scan for remote endpoints with the specified serviceId.
stopBroadcastingFuture<void>Stops broadcasting.
stopScanFuture<void>Stops discovering devices.
disconnectAllFuture<void>Disconnects all connections.
connectOnEstablishStream<ConnectOnEstablishResponse>Returns a stream that fires events when a connection has been established and both ends need to confirm whether to accept the connection.
connectOnResultStream<ConnectOnResultResponse>Returns a stream that fires events when either end accepts or rejects the connection.
connectOnDisconnectedStream<String>Returns a stream that fires events when the remote endpoint disconnects or the connection is unreachable.
scanOnFoundStream<ScanOnFoundResponse>Returns a stream that fires events when an endpoint is discovered.
scanOnLostStream<String>Returns a stream that fires events when an endpoint is no longer discoverable.

Methods

static HMSDiscoveryEngine get instance

Obtains the singleton instance of the class.

Return Type
TypeDescription
HMSDiscoveryEngineSingleton instance of the class.
Call Example
instance = HMSDiscoveryEngine.instance;
Future<void> acceptConnect(String endpointId)

Accepts a connection. This API must be called before data transmission. If the connection request is not accepted within 8 seconds, the connection fails and needs to be re-initiated.

  • STATUS_SUCCESS: The connection is accepted.
  • STATUS_ALREADY_CONNECTED: The app has already been connected to the remote endpoint.
Parameters
ParameterTypeDescription
endpointIdStringID of the remote endpoint.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSDiscoveryEngine.instance.acceptConnect('com.example.myapplication');
Future<void> disconnect(String endpointId)

Disconnects from a remote endpoint. Once this API is called, this endpoint cannot send or receive data.

Parameters
ParameterTypeDescription
endpointIdStringID of the remote endpoint.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await HMSDiscoveryEngine.instance.disconnect('com.example.myapplication');
Future<void> rejectConnect(String endpointId)

Rejects a connection request from a remote endpoint.

  • STATUS_SUCCESS: The connection is successfully rejected.
  • STATUS_ALREADY_CONNECTED: The app has already been connected to the remote endpoint.
Parameters
ParameterTypeDescription
endpointIdStringID of the remote endpoint.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSDiscoveryEngine.instance.rejectConnect('com.example.myapplication');
Future<void> requestConnect({String name, String endpointId})

Sends a request to connect to a remote endpoint.

  • STATUS_SUCCESS: The connection request is sent.
  • STATUS_ALREADY_CONNECTED: The app has already been connected to the remote endpoint.
  • STATUS_BLUETOOTH_OPERATION_FAILED: The connection failed due to a Bluetooth error.
  • STATUS_FAILURE: The connection failed due to another reason.
Parameters
ParameterTypeDescription
nameStringLocal endpoint name.
endpointIdStringID of the remote endpoint.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSDiscoveryEngine.instance
          .requestConnect(name: 'endpointName', endpointId: 'com.example.myapplication');
Future<void> startBroadcasting({String name, String serviceId, BroadcastOption broadcastOption})

Starts broadcasting. The result codes are described as follows:

  • STATUS_SUCCESS: Broadcasting started successfully.
  • STATUS_ALREADY_BROADCASTING: Broadcasting is going on.
  • STATUS_API_DISORDER: API calls are out of order.
  • STATUS_MISSING_PERMISSION_ACCESS_COARSE_LOCATION: The location permission is missing.
Parameters
ParameterTypeDescription
nameStringLocal endpoint name.
serviceIdStringService ID. The app package name is recommended.
broadcastOptionStringBroadcasting options specified in the connection policy.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSDiscoveryEngine.instance.startBroadcasting(
    name: "MY-SERVICE",
    serviceId: "com.example.myapplication",
    broadcastOption: BroadcastOption(DiscoveryPolicy.p2p),
);
Future<void> startScan({String serviceId, ScanOption scanOption})

Starts to scan for remote endpoints with the specified service ID. The result codes are described as follows:

  • STATUS_SUCCESS: Scanning started successfully.
  • STATUS_ALREADY_SCANNING: The app has discovered the service.
  • STATUS_API_DISORDER: API calls are out of order.
  • STATUS_MISSING_PERMISSION_ACCESS_COARSE_LOCATION: The location permission is missing.
Parameters
ParameterTypeDescription
serviceIdStringService ID. The app package name is recommended.
scanOptionScanOptionScanning options specified in the connection policy.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
 await HMSDiscoveryEngine.instance.startScan(
          serviceId: "com.example.myapplication", scanOption: ScanOption(DiscoveryPolicy.p2p));
Future<void> stopBroadcasting()

Stops broadcasting.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
 await HMSDiscoveryEngine.instance.stopBroadcasting();
Future<void> stopScan()

Stops discovering devices.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
 await HMSDiscoveryEngine.instance.stopScan();
Future<void> disconnectAll()

Disconnects all connections.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
 await HMSDiscoveryEngine.instance.disconnectAll();
Stream<ConnectOnEstablishResponse> get connectOnEstablish

Returns a stream that fires events when a connection has been established and both ends need to confirm whether to accept the connection.

Return Type
TypeDescription
Stream<ConnectOnEstablishResponse>A stream that fires events when a connection has been established and both ends need to confirm whether to accept the connection.
Call Example
 HMSDiscoveryEngine.instance.connectOnEstablish
    .listen((ConnectOnResultResponse response) {
  // Perform operations
});
Stream<ConnectOnResultResponse> get connectOnResult

Returns a stream that fires events when either end accepts or rejects the connection.

Return Type
TypeDescription
Stream<ConnectOnResultResponse>A stream that fires events when either end accepts or rejects the connection. ConnectOnResultResponse indicates whether the remote point accepts or rejects the connection. You can call the connectResult.statusCode property of the ConnectOnResultResponse class to obtain the status code STATUS_SUCCESS or STATUS_CONNECT_REJECTED.
Call Example
 HMSDiscoveryEngine.instance.connectOnResult
    .listen((ConnectOnResultResponse response) {
  // Perform operations
});
Stream<String> get connectOnDisconnected

Returns a stream that fires events when the remote endpoint disconnects or the connection is unreachable.

Return Type
TypeDescription
Stream<String>A stream that fires events when the remote endpoint disconnects or the connection is unreachable.
Call Example
 HMSDiscoveryEngine.instance.connectOnDisconnected
    .listen((String endpoint) {
  // Perform operations
});
Stream<ScanOnFoundResponse> get scanOnFound

Returns a stream that fires events when an endpoint is discovered.

Return Type
TypeDescription
Stream<ScanOnFoundResponse>A stream that fires events when an endpoint is discovered. ScanOnFoundResponse indicates the ID of the remote endpoint and information about the discovered endpoint.
Call Example
 HMSDiscoveryEngine.instance.scanOnFound
        .listen((ScanOnFoundResponse response) {
      // Perform operations
    });
Stream<String> get scanOnLost

Returns a stream that fires events when an endpoint is no longer discoverable. The method applies only to endpoints for which scanOnFound is called.

Return Type
TypeDescription
Stream<String>A stream that fires events when an endpoint is discovered. The string value is the ID of the remote endpoint.
Call Example
 HMSDiscoveryEngine.instance.scanOnLost
        .listen((ScanOnFoundResponse response) {
      // Perform operations
    });

BleSignal #

Obtains the BLE signal.

Constants

NameTypeDescriptionValue
bleUnknownTxPowerintUnknown transmit power level.0x80

Properties

NameTypeDescription
rssifinal intReceived signal strength in dBm. The value range is [–127,127].
txPowerfinal intTransmit power from 1 m away, in dBm.

Constructor Summary

ConstructorDescription
BleSignal({int rssi, int txPower})BleSignal constructor.
BleSignal.fromMap(Map<String, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

BleSignal({int rssi, int txPower})

Constructs a BleSignal instance. For parameter descriptions, see class properties.

factory BleSignal.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
signal = BleSignal({rssi: 13, txPower: 35});
Map<String, dynamic> map = signal.toMap();

BroadcastOption #

Obtains options for broadcasting.

Properties

NameTypeDescription
policyfinal DiscoveryPolicyThe current policy of the BroadcastOption object.

Constructor Summary

ConstructorDescription
BroadcastOption(DiscoveryPolicy policy)BroadcastOption constructor.
BroadcastOption.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

BroadcastOption(DiscoveryPolicy policy)

Constructs a BroadcastOption instance. For parameter descriptions, see class properties.

factory BroadcastOption.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = BroadcastOption(DiscoveryPolicy.p2p).equals(object);
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
option = BroadcastOption(DiscoveryPolicy.p2p);
Map<String, dynamic> map = option.toMap();

ConnectInfo #

Obtains the information about a connection.

Properties

NameTypeDescription
endpointNamefinal StringThe name of the remote endpoint.
authCodefinal StringThe symmetric authentication codes from both ends.
isRemoteConnectfinal boolIf the connection request is initiated by the remote endpoint, true. Otherwise, false.

Constructor Summary

ConstructorDescription
ConnectInfo({String endpointName, String authCode, bool isRemoteConnect})ConnectInfo constructor.
ConnectInfo.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ConnectInfo({String endpointName, String authCode, bool isRemoteConnect})

Constructs a ConnectInfo instance. For parameter descriptions, see class properties.

factory ConnectInfo.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
info = ConnectInfo({endpointName: 'name', authCode: 'code', isRemoteConnect: true});
Map<String, dynamic> map = info.toMap();

ConnectResult #

Returns the connection result.

Properties

NameTypeDescription
statusCodefinal intThe connection status code, which can be STATUS_SUCCESS or STATUS_CONNECT_REJECTED.

Constructor Summary

ConstructorDescription
ConnectResult(int statusCode)ConnectResult constructor.
ConnectResult.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ConnectResult(int statusCode)

Constructs a ConnectInfo instance. For parameter descriptions, see class properties.

factory ConnectResult.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
result = ConnectResult(8010);
Map<String, dynamic> map = result.toMap();

DiscoveryPolicy #

Obtains the policy used for nearby device broadcasting and scanning.

Constants

NameTypeDescriptionValue
meshDiscoveryPolicyPoint-to-point connection policy, which supports an M-to-N connection topology.MESH
p2pDiscoveryPolicyPoint-to-point connection policy, which supports a 1-to-1 connection topology.P2P
starDiscoveryPolicyPoint-to-point connection policy, which supports a 1-to-N connection topology.STAR

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a policy into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = DiscoveryPolicy.p2p.equals(object);
@override String toString()

Converts a policy into a readable character string.

Return Type
TypeDescription
StringA policy converted to a readable character string.
Call Example
String desc = DiscoveryPolicy.p2p.toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = DiscoveryPolicy.p2p.toMap();

Distance #

Provides distance information.

Constants

NameTypeDescriptionValue
precisionLowintPrecision of the distance estimated based on the BLE signal strength.1
unknownDistanceUnknown distance.precision: 1, meters: double.nan

Properties

NameTypeDescription
precisionintPrecision of the estimated instance.
metersdoubleEstimated distance, in m.

Constructor Summary

ConstructorDescription
Distance({int precision, double meters})Distance constructor.
Distance.fromMap(Map<String, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

Distance({int precision, double meters})

Constructs a Distance instance. For parameter descriptions, see class properties.

Distance.fromMap(Map<String, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = Distance.unknown.toMap();

ScanEndpointInfo #

Obtains the information about the discovered endpoint.

Properties

NameTypeDescription
serviceIdfinal StringUnique ID of the app, which is usually the app package name.
namefinal StringName of the discovered endpoint.

Constructor Summary

ConstructorDescription
ScanEndpointInfo({String serviceId, String name})ScanEndpointInfo constructor.
ScanEndpointInfo.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ScanEndpointInfo(int statusCode)

Constructs a ScanEndpointInfo instance. For parameter descriptions, see class properties.

factory ScanEndpointInfo.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
info = ScanEndpointInfo({serviceId: 'name', name: 'code'});
Map<String, dynamic> map = info.toMap();

ScanOption #

Obtains options for scanning devices.

Properties

NameTypeDescription
policyfinal DiscoveryPolicyThe current policy of the ScanOption object.

Constructor Summary

ConstructorDescription
ScanOption(DiscoveryPolicy policy)ScanOption constructor.
ScanOption.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ScanOption(DiscoveryPolicy policy)

Constructs a ScanOption instance. For parameter descriptions, see class properties.

factory ScanOption.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether the other object is equal to this object.
Call Example
bool equals = ScanOption(DiscoveryPolicy.p2p).equals(object);
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
option = ScanOption(DiscoveryPolicy.p2p);
Map<String, dynamic> map = option.toMap();

ConnectOnEstablishResponse #

Response class for the connectOnEstablish events.

Properties

NameTypeDescription
endpointIdfinal StringID of the remote endpoint.
connectInfofinal ConnectInfoConnection information.

Constructor Summary

ConstructorDescription
ConnectOnEstablishResponse({String endpointId, ConnectInfo connectInfo})ConnectOnEstablishResponse constructor.
ConnectOnEstablishResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ConnectOnEstablishResponse({String endpointId, ConnectInfo connectInfo})

Constructs a ConnectOnEstablishResponse instance. For parameter descriptions, see class properties.

factory ConnectOnEstablishResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
response = ConnectOnEstablishResponse.fromMap(map);
Map<String, dynamic> map = response.toMap();

ConnectOnResultResponse #

Response class for the connectOnResult events.

Properties

NameTypeDescription
endpointIdfinal StringID of the remote endpoint.
connectResultfinal ConnectResultIndicates whether the remote point accepts or rejects the connection. You can call the statusCode property of the ConnectResult class to obtain the status code STATUS_SUCCESS or STATUS_CONNECT_REJECTED.

Constructor Summary

ConstructorDescription
ConnectOnResultResponse({String endpointId, ConnectResult connectResult})ConnectOnResultResponse constructor.
ConnectOnResultResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ConnectOnResultResponse({String endpointId, ConnectResult connectResult})

Constructs a ConnectOnEstablishResponse instance. For parameter descriptions, see class properties.

factory ConnectOnResultResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
response = ConnectOnResultResponse.fromMap(map);
Map<String, dynamic> map = response.toMap();

ScanOnFoundResponse #

Response class for the scanOnFound events.

Properties

NameTypeDescription
endpointIdfinal StringID of a remote endpoint.
scanEndpointInfofinal ScanEndpointInfoInformation about the discovered endpoint.

Constructor Summary

ConstructorDescription
ScanOnFoundResponse({String endpointId, ScanEndpointInfo scanEndpointInfo})ScanOnFoundResponse constructor.
ScanOnFoundResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

ScanOnFoundResponse({String endpointId, ConnectInfo connectInfo})

Constructs a ScanOnFoundResponse instance. For parameter descriptions, see class properties.

factory ScanOnFoundResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
response = ScanOnFoundResponse.fromMap(map);
Map<String, dynamic> map = response.toMap();

Transfer Engine #

This section contains the classes related to the Transfer Engine.

HMSTransferEngine #

An entry class for data transmission. This class implements related transmission methods.

Constants

NameTypeDescriptionValue
maxSizeDataintMaximum length of bytes that can be sent when the sendData method is called.32768

Method Summary

MethodReturn TypeDescription
instanceHMSTransferEngineObtains the singleton instance of the class.
sendDataFuture<void>Sends data.
sendMultiEndpointDataFuture<void>Sends data to multiple endpoints specified in a list. The method is a variation of the preceding method.
cancelDataTransferFuture<void>Cancels data transmission when sending or receiving data.
dataOnReceivedStreamReturns a stream that fires events when a TransferData instance is received.
dataOnTransferUpdateStreamReturns a stream that fires events that allows to obtaing the data sending or receiving status.

Methods

static HMSTransferEngine get instance

Obtains the singleton instance of the class.

Return Type
TypeDescription
HMSTransferEngineSingleton instance of the class.
Call Example
instance = HMSTransferEngine.instance;
Future<void> sendData(String endpointId, TransferData data, {bool isUri = false})

Sends data. The method can be called only when a connection has been successfully established. The result codes are as follows:

  • STATUS_API_DISORDER: API calls are out of order.
  • STATUS_ENDPOINT_UNKNOWN: No connection is set up.
  • STATUS_SUCCESS: Data sending started successfully, which does not mean data sending completion. Data sending result can be obtained by calling onDataTransferUpdate.
  • STATUS_MISSING_PERMISSION_FILE_READ_WRITE: The read and write permissions on the file are missing.
Parameters
ParameterTypeDescription
endpointIdStringID of the remote endpoint.
dataTransferDataData to be sent.
isUriboolWhether the provided data path is a Uri. Applies to TransferDataFile and TransferDataStream.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
TransferData data = TransferData.fromBytes(utf8.encode('Hello there!'));
await HMSTransferEngine.instance.sendData(_endpointId, data);
Future<void> sendMultiEndpointData(List<String> endpointIds, TransferData data, {bool isUri = false})

Sends data to multiple endpoints specified in a list. The method is a variation of the preceding method.

The method can be called only when a connection has been successfully established. The result codes are as follows:

  • STATUS_API_DISORDER: API calls are out of order.
  • STATUS_ENDPOINT_UNKNOWN: No connection is set up.
  • STATUS_SUCCESS: Data sending started successfully, which does not mean data sending completion. Data sending result can be obtained by calling onDataTransferUpdate.
  • STATUS_MISSING_PERMISSION_FILE_READ_WRITE: The read and write permissions on the file are missing.
Parameters
ParameterTypeDescription
endpointIdsList<String>Remote endpoint ID list.
dataTransferDataData to be sent.
isUriboolWhether the provided data path is a Uri. Applies to TransferDataFile and TransferDataStream.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
List<String> _endpointIds = ['app1','app2','app3'];
TransferData data = TransferData.fromBytes(utf8.encode('Hello there!'));
await HMSTransferEngine.instance.sendData(_endpointIds, data);
Future<void> cancelDataTransfer(int dataId)

Cancels data transmission when sending or receiving data.

Parameters
ParameterTypeDescription
dataIdStringID of the data whose transmission is to be cancelled.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await HMSTransferEngine.instance.cancelDataTransfer(12345);
Stream<DataOnReceivedResponse> get dataOnReceived

Returns a stream that fires events when a TransferData instance is received.

Return Type
TypeDescription
Stream<DataOnReceivedResponse>A stream that fires events when a TransferData instance is received. DataOnReceivedResponse contains the ID of the remote endpoint, the transferred data and an error code if there was an error during data parsing. The error code will be null otherwise.
Call Example
HMSTransferEngine.instance.dataOnReceived
    .listen((DataOnReceivedResponse response) {
    // Perform operations
});
Stream<DataOnTransferUpdateResponse> get dataOnTransferUpdate

Returns a stream that fires events that allows to obtain the data sending or receiving status.

Return Type
TypeDescription
Stream<DataOnTransferUpdateResponse>A stream that fires events that allows to obtain the data sending or receiving status. DataOnTransferUpdateResponse contains the ID of the remote endpoint and a TransferStateUpdate object provides information about transmission status.
Call Example
HMSTransferEngine.instance.dataOnTransferUpdate
    .listen((DataOnTransferUpdateResponse response) {
    // Perform operations
});

TransferData #

A payload class. The payload needs to be sent and received in the same type.

Properties

NameTypeDescription
idintUnique ID of the payload.
typeintRepresents the payload type.
bytesfinal Uint8ListByte array. Used if data type is Bytes, otherwise null.
filefinal TransferDataFileObtains a payload of the file type. Used if data type is File, otherwise null.
streamfinal TransferDataStreamObtains a payload of the stream type. Used if data type is Stream, otherwise null.
hashintHash value of the data object that was created and transferred on the platform side. This value will be returned to Flutter with the callbacks that return information on the transferred data, otherwise is null.

Constructor Summary

ConstructorDescription
TransferData({int id, int type, Uint8List bytes, TransferDataStream stream, TransferDataFile file, int hash})TransferData constructor.
TransferData.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.
TransferData.dataBytesFactory(Uint8List bytes, int id)Creates a data instance of the byte type.
TransferData.dataFileFactory(TransferDataFile file, int id)Creates a data instance of the file type.
TransferData.dataStreamFactory(TransferDataStream stream, int id)Creates a data instance of the stream type.
TransferData.fromBytes(Uint8List bytes)Creates a payload of the data packet type.
TransferData.fromStream({String url, Uint8List content})Creates a payload of the stream type.
TransferData.fromFile(String filePath, [int size])Creates a payload of the file type.

Method Summary

MethodReturn TypeDescription
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Constructors

TransferData({int id, int type, Uint8List bytes, TransferDataStream stream, TransferDataFile file, int hash})

Constructs a TransferData instance. For parameter descriptions, see class properties.

factory TransferData.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

factory TransferData.dataBytesFactory(Uint8List bytes, int id)

Creates a data instance of the byte type.

Parameters
ParameterTypeDescription
bytesUint8ListByte array.
idintData ID.
factory TransferData.dataFileFactory(TransferDataFile file, int id)

Creates a data instance of the file type.

Parameters
ParameterTypeDescription
fileTransferDataFileFile to be read.
idintData ID.
factory TransferData.dataStreamFactory(TransferDataStream stream, int id)

Creates a data instance of the stream type.

Parameters
ParameterTypeDescription
fileTransferDataStreamStream data.
idintData ID.
factory TransferData.fromBytes(Uint8List bytes)

Creates a payload of the data packet type. Data ID will be randomly generated on the platform side.

Parameters
ParameterTypeDescription
bytesUint8ListByte array.
factory TransferData.fromStream({String url, Uint8List content})

Creates a payload of the stream type. Data ID will be randomly generated on the platform side.

Parameters
ParameterTypeDescription
urlStringURL or Uri for the stream. Has precedence over content.
contentUint8ListByte array content of the stream. Used if url is null.
factory TransferData.fromFile(String filePath, [int size])

Creates a payload of the file type. Data ID will be randomly generated on the platform side.

Parameters
ParameterTypeDescription
filePathStringPath to the file on the device. Can also be a Uri.
sizeintFile size. Optional.
Parameters
ParameterTypeDescription
fileTransferDataFileStream data.
idintData ID.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
TransferData data = TransferData.fromBytes(utf8.encode('Hello there!'));
Map<String, dynamic> map = data.toMap();

TransferDataStream #

Represents the data stream.

Properties

NameTypeDescription
urlStringURL or URI for the stream to be transferred. Only used when sending data. Meaning, for TransferData objects that are returned with dataOnReceived, this will always be null.
contentUint8ListJava InputStream converted to a byte array. This is the data that will be transferred when sendData is called, if url is null.

Constructor Summary

ConstructorDescription
TransferDataStream({String url, Uint8List content})TransferDataStream constructor.
TransferDataStream.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Constructors

TransferDataStream({String url, Uint8List content})

Constructs a TransferDataStream instance. For parameter descriptions, see class properties.

factory TransferDataStream.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
TransferDataStream data = TransferDataStream.fromMap(map);
Map<String, dynamic> map = data.toMap();

TransferDataFile #

Represents the local file.

Properties

NameTypeDescription
filePathStringPath to the file on the device. Can also be a Uri.
sizeintFile size. Specifying this property when sending data will have no effect on the platform size. Actual size of the file will be accessible to Flutter with the response that is returned by the dataOnReceived stream.

Constructor Summary

ConstructorDescription
TransferDataFile({String filePath, int size})TransferDataFile constructor.
TransferDataFile.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Constructors

TransferDataFile({String filePath, int size})

Constructs a TransferDataFile instance. For parameter descriptions, see class properties.

factory TransferDataFile.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
TransferDataFile data = TransferDataFile.fromMap(map);
Map<String, dynamic> map = data.toMap();

TransferStateUpdate #

Updates the data transmission status.

Properties

NameTypeDescription
statusfinal intTransmission status.
dataIdfinal intData ID.
totalBytesfinal intTotal number of bytes to transfer.
bytesTransferredfinal intNumber of transferred bytes.
hashfinal intHash value of the data object that was created and transferred on the platform side.

Constructor Summary

ConstructorDescription
TransferStateUpdate({int status, int dataId, int totalBytes, int bytesTransferred, int hash})TransferStateUpdate constructor.
TransferStateUpdate.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Constructors

TransferStateUpdate({int status, int dataId, int totalBytes, int bytesTransferred, int hash})

Constructs a TransferStateUpdate instance. For parameter descriptions, see class properties.

factory TransferStateUpdate.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
TransferStateUpdate stateUpdate = TransferStateUpdate.fromMap(map); 
bool equals = stateUpdate.equals(object);
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
TransferStateUpdate data = TransferStateUpdate.fromMap(map);
Map<String, dynamic> map = data.toMap();

DataOnReceivedResponse #

Response class for the dataOnReceived events.

Properties

NameTypeDescription
endpointIdfinal StringID of a remote endpoint.
datafinal TransferDataTransferred data.
errorCodefinal StringUsed if there was an error during data parsing, otherwise null.

Constructor Summary

ConstructorDescription
DataOnReceivedResponse({String endpointId, TransferData data, String errorCode})DataOnReceivedResponse constructor.
DataOnReceivedResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Constructors

DataOnReceivedResponse({String endpointId, TransferData data, String errorCode})

Constructs a DataOnReceivedResponse instance. For parameter descriptions, see class properties.

factory DataOnReceivedResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
DataOnReceivedResponse data = DataOnReceivedResponse.fromMap(map);
Map<String, dynamic> map = data.toMap();

DataOnTransferUpdateResponse #

Response class for the dataOnTransferUpdate events.

Properties

NameTypeDescription
endpointIdfinal StringID of a remote endpoint.
transferStateUpdateTransferStateUpdateUpdates the data transmission status.

Constructor Summary

ConstructorDescription
DataOnTransferUpdateResponse({String endpointId, TransferStateUpdate transferStateUpdate})DataOnTransferUpdateResponse constructor.
DataOnTransferUpdateResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Constructors

DataOnTransferUpdateResponse({String endpointId, TransferStateUpdate transferStateUpdate})

Constructs a DataOnTransferUpdateResponse instance. For parameter descriptions, see class properties.

factory DataOnTransferUpdateResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
DataOnTransferUpdateResponse data = DataOnTransferUpdateResponse.fromMap(map);
Map<String, dynamic> map = data.toMap();

Wifi Share Engine #

This section contains the classes related to the Wifi Share Engine.

HMSWifiShareEngine #

An entry class for Wi-Fi sharing. This class provides APIs for Wi-Fi sharing.

Method Summary

MethodReturn TypeDescription
instanceHMSWifiShareEngineObtains the singleton instance of the class.
startWifiShareFuture<void>Enables the Wi-Fi sharing function. Set WifiSharePolicy based on function requirements.
stopWifiShareFuture<void>Disables the Wi-Fi sharing function.
shareWifiConfigFuture<void>Shares Wi-Fi with a remote endpoint.
wifiOnFoundStream<WifiOnFoundResponse>Returns a stream that fires events when a nearby endpoint on which Wi-Fi can be configured is discovered. Endpoint information can be obtained for the display and selection of target endpoints.
wifiOnLostStream<String>Returns a stream that fires events when an endpoint on which Wi-Fi can be configured is lost.
wifiOnFetchAuthCodeStream<WifiOnFetchAuthCodeResponse>Returns a stream that fires events when the verification code for Wi-Fi sharing is obtained. The verification code must be obtained and displayed so that users can confirm the target endpoint.
wifiOnShareResultStream<WifiShareResultResponse>Returns a stream that fires events when the Wi-Fi sharing result is obtained.

Methods

static HMSWifiShareEngine get instance

Obtains the singleton instance of the class.

Return Type
TypeDescription
HMSWifiShareEngineSingleton instance of the class.
Call Example
instance = HMSWifiShareEngine.instance;
Future<void> startWifiShare(WifiSharePolicy policy)

Enable the Wi-Fi sharing function. Set WifiSharePolicy based on function requirements.

Parameters
ParameterTypeDescription
policyWifiSharePolicyWi-Fi sharing policy. Enable the Wi-Fi sharing mode or configuration mode as required.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSWifiShareEngine.instance.startWifiShare(WifiSharePolicy.set);
Future<void> stopWifiShare()

Disables the Wi-Fi sharing function.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
 await HMSWifiShareEngine.instance.stopWifiShare();
Future<void> shareWifiConfig(String endpointId)

Shares Wi-Fi with a remote endpoint.

Parameters
ParameterTypeDescription
endpointIdStringID of a remote endpoint.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSWifiShareEngine.instance.shareWifiConfig('com.example.myapplication');
Stream<WifiOnFoundResponse> get wifiOnFound

Returns a stream that fires events when a nearby endpoint on which Wi-Fi can be configured is discovered. Endpoint information can be obtained for the display and selection of target endpoints.

Return Type
TypeDescription
Stream<WifiOnFoundResponse>A stream that fires events when a nearby endpoint on which Wi-Fi can be configured is discovered. WifiOnFoundResponse contains the information for the display and selection of target endpoints.
Call Example
HMSWifiShareEngine.instance.wifiOnFound
    .listen((WifiOnFoundResponse response) {
  // Perform operations
});
Stream<String> get wifiOnLost

Returns a stream that fires events when an endpoint on which Wi-Fi can be configured is lost.

Return Type
TypeDescription
Stream<String>A stream that fires events when an endpoint on which Wi-Fi can be configured is lost. The string value is the ID of the remote endpoint.
Call Example
HMSWifiShareEngine.instance.wifiOnLost.listen((String endpointId) {
  // Perform operations
});
Stream<WifiOnFetchAuthCodeResponse> get wifiOnFetchAuthCode

Returns a stream that fires events when the verification code for Wi-Fi sharing is obtained. The verification code must be displayed on the UI so that users can confirm the target endpoint.

Return Type
TypeDescription
Stream<WifiOnFetchAuthCodeResponse>A stream that fires events when the verification code for Wi-Fi sharing is obtained. WifiOnFetchAuthCodeResponse contains the ID of the remote endpoint and the verification code.
Call Example
HMSWifiShareEngine.instance.wifiOnFetchAuthCode
    .listen((WifiOnFetchAuthCodeResponse response) {
  // Perform operations
});
Stream<WifiShareResultResponse> get wifiOnShareResult

Returns a stream that fires events that return Wi-Fi sharing results.

Return Type
TypeDescription
Stream<WifiShareResultResponse>A stream that fires events that return Wi-Fi sharing results. WifiShareResultResponse contains the ID of the remote endpoint and a status code that indicates Wi-Fi configuration result.
Call Example
HMSWifiShareEngine.instance.wifiOnShareResult
    .listen((WifiShareResultResponse response) {
  // Perform operations
});

WifiSharePolicy #

A Wi-Fi sharing policy class. The options are the Wi-Fi sharing mode and Wi-Fi configuration mode.

Constants

NameTypeDescriptionValue
shareWifiSharePolicyWi-Fi sharing mode.SHARE
setWifiSharePolicyWi-Fi configuration mode.SET

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a policy into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = WifiSharePolicy.share.equals(object);
@override String toString()

Converts the WifiSharePolicy object into a readable character string.

Return Type
TypeDescription
StringWifiSharePolicy object into a readable character string.
Call Example
String desc = WifiSharePolicy.share.toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = WifiSharePolicy.share.toMap();

WifiOnFoundResponse #

Response class for the wifiOnFound events.

Properties

NameTypeDescription
endpointIdfinal StringID of a remote endpoint.
scanEndpointInfofinal ScanEndpointInfoInformation about the discovered endpoint.

Constructor Summary

ConstructorDescription
WifiOnFoundResponse({String endpointId, ScanEndpointInfo scanEndpointInfo})WifiOnFoundResponse constructor.
WifiOnFoundResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

WifiOnFoundResponse({String endpointId, ConnectInfo connectInfo})

Constructs a WifiOnFoundResponse instance. For parameter descriptions, see class properties.

factory WifiOnFoundResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
response = WifiOnFoundResponse.fromMap(map);
Map<String, dynamic> map = response.toMap();

WifiOnFetchAuthCodeResponse #

Response class for the wifiOnFetchAuthCode events.

Properties

NameTypeDescription
endpointIdfinal StringID of a remote endpoint.
authCodefinal StringWi-Fi sharing verification code.

Constructor Summary

ConstructorDescription
WifiOnFetchAuthCodeResponse({String endpointId, String authCode})WifiOnFetchAuthCodeResponse constructor.
WifiOnFetchAuthCodeResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

WifiOnFetchAuthCodeResponse({String endpointId, String authCode})

Constructs a WifiOnFetchAuthCodeResponse instance. For parameter descriptions, see class properties.

factory WifiOnFetchAuthCodeResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
response = WifiOnFetchAuthCodeResponse.fromMap(map);
Map<String, dynamic> map = response.toMap();

WifiShareResultResponse #

Response class for the wifiOnShareResult events.

Properties

NameTypeDescription
endpointIdfinal StringID of a remote endpoint.
statusCodefinal intWi-Fi configuration result status code.

Constructor Summary

ConstructorDescription
WifiShareResultResponse({String endpointId, int statusCode})WifiShareResultResponse constructor.
WifiShareResultResponse.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

WifiShareResultResponse({String endpointId, int statusCode})

Constructs a WifiShareResultResponse instance. For parameter descriptions, see class properties.

factory WifiShareResultResponse.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
response = WifiShareResultResponse.fromMap(map);
Map<String, dynamic> map = response.toMap();

Message Engine #

This section contains the classes related to the Message Engine.

HMSMessageEngine #

Defines a set of APIs to publish or subscribe to messages between nearby devices. The APIs do not require HUAWEI ID authentication to perform operations. However, you need to apply for API_KEY on HUAWEI Developers. Other than getPending, all of the APIs need to be used from a foreground activity. You need to symmetrically call put or unput, get or unget, and getPending or ungetPending.

Method Summary

MethodReturn TypeDescription
instanceHMSMessageEngineObtains the singleton instance of the class.
putFuture<void>Publishes a message and broadcasts a sharing code for nearby devices to scan.
putWithOptionFuture<void>Publishes a message and broadcasts a sharing code for nearby devices to scan.
registerStatusCallbackFuture<void>Registers a status callback function, which will notify your app of key events.
getFuture<void>Obtains messages from the cloud using the default option.
getWithOptionFuture<void>Subscribes to messages published by a nearby device. Only messages of the same app can be subscribed to.
getPendingFuture<void>Identifies only BLE beacon messages.
unputFuture<void>Cancels message publishing.
unregisterStatusCallbackFuture<void>Cancels the status callback registered before.
ungetPendingFuture<void>Cancels the current message subscription.
ungetFuture<void>Cancels a message subscription.
disposeFuture<void>Cancels the stream subscription of the Message Engine and clears callback objects.

Methods

static HMSMessageEngine get instance

Obtains the singleton instance of the class.

Return Type
TypeDescription
HMSMessageEngineSingleton instance of the class.
Call Example
instance = HMSMessageEngine.instance;
Future<void> put(Message message)

Publishes a message and broadcasts a token for nearby devices to scan.

Parameters
ParameterTypeDescription
messageMessagePublished message.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
Message _message = Message(content: utf8.encode("Hello there!"));
await HMSMessageEngine.instance.put(_message);
Future<void> putWithOption(Message message, MessagePutOption putOption)

Publishes a message and broadcasts a token for nearby devices to scan. This message is published only to apps that use the same project ID and have registered the message type with the cloud for subscription.

Parameters
ParameterTypeDescription
messageMessagePublished message.
putOptionMessagePutOptionMessagePutOption parameters.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
MessagePutOption option = MessagePutOption(
    policy: MessagePolicyBuilder().build(),
    putCallback: MessagePutCallback(
      onTimeout: () => {/* Perform operations */},
    ));
await HMSMessageEngine.instance.putWithOption(msg, option);
Future<void> registerStatusCallback(MessageStatusCallback statusCallback)

Registers a status callback function, which will notify your app of key events. When your app calls one of the APIs for the first time, the function will return the status.

Parameters
ParameterTypeDescription
statusCallbackMessageStatusCallbackA callback class for MessageEngine status changes.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
_statusCb = MessageStatusCallback(
  onPermissionChanged: (bool granted) => {/* Perform operations */},
);
await HMSMessageEngine.instance.registerStatusCallback(_statusCb);
Future<void> get(NearbyMessageHandler handler)

Obtains messages from the cloud using the default option.

Parameters
ParameterTypeDescription
handlerNearbyMessageHandlerNearbyMessageHandler implementation to obtain callbacks of received messages.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
_handler = NearbyMessageHandler(onBleSignalChanged: (message, signal) {
  // Perform operations
}, onDistanceChanged: (Message message, Distance distance) {
  // Perform operations
}, onFound: (Message message) {
  // Perform operations
}, onLost: (Message message) {
  // Perform operations
});
await HMSMessageEngine.instance.get(_handler);
Future<void> getWithOption(NearbyMessageHandler handler, MessageGetOption getOption)

Registers the messages to be obtained with the cloud. Only messages with the same project ID can be obtained.

Parameters
ParameterTypeDescription
handlerNearbyMessageHandlerNearbyMessageHandler implementation to obtain callbacks of received messages.
getOptionMessageGetOptionMessageGetOption parameters.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
MessageGetOption option = MessageGetOption(
    policy: MessagePolicyBuilder().build(),
    getCallback: MessageGetCallback(
      onTimeout: () => {/* Perform operations */},
    ));
await HMSMessageEngine.instance.getWithOption(handler, option);
Future<void> getPending(NearbyMessageHandler handler, [MessageGetOption option])

Identifies only BLE beacon messages. It subscribes to messages published by nearby devices in a persistent and low-power manner and uses the default configuration. Scanning is going on no matter whether your app runs in the background or foreground. The scanning stops when the app process is killed.

Parameters
ParameterTypeDescription
handlerNearbyMessageHandlerNearbyMessageHandler implementation to obtain callbacks of received messages. Currently, only the onFound and onLost methods are supported.
getOptionMessageGetOptionMessageGetOption parameters.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSMessageEngine.instance.getPending(NearbyMessageHandler(
  onFound: (message) {
    // Perform operations
  },
  onLost: (message) {
    // Perform operations         
  },
));
Future<void> unput(Message message, [MessagePutOption putOption]) async

Cancels message publishing.

Paramaters
ParameterTypeDescription
messageMessagePublished message.
putOptionMessagePutOptionPreviously used MessagePutOption parameters.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
Message _message = Message(content: utf8.encode("Hello there!"));
await HMSMessageEngine.instance.unput(_message);
Future<void> unregisterStatusCallback(MessageStatusCallback statusCallback) async

Cancels the status callback registered before.

Paramaters
ParameterTypeDescription
statusCallbackMessageStatusCallbackStatus callback registered before.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSMessageEngine.instance.unregisterStatusCallback(_statusCb);
Future<void> ungetPending() async

Cancels a registered message subscription task.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSMessageEngine.instance.ungetPending();
Future<void> unget(NearbyMessageHandler handler, [MessageGetOption getOption]) async

Cancels the current message subscription.

Paramaters
ParameterTypeDescription
handlerNearbyMessageHandlerCallback processing class registered by the current task when the target message is subscribed.
getOptionMessageGetOptionPreviously used MessageGetOption parameters.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value. Throws platform exception otherwise.
Call Example
await HMSMessageEngine.instance.unget(_handler);
Future<void> dispose() async

Cancels the stream subscription of the Message Engine and clears callback objects.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
HMSMessageEngine.instance.dispose();

Message #

Obtains the message that will be shared with nearby devices. The message consists of client-specified content and a type. The type can be used in MessagePickerBuilder to limit which messages an app can receive in a subscription.

Constants

NameTypeDescriptionValue
maxContentSizeintMaximum size of the message content.65536
maxTypeLengthintMaximum size of a message type.16
messageNamespaceReservedStringNamespace reserved for special messages._reserved_namespace
messageTypeEddystoneUidStringMessage type of EddystoneUid beacons._eddystone_uid
messageTypeIBeaconIdStringMessage type of IBeaconId beacons._ibeacon_id

Properties

NameTypeDescription
contentUint8ListMessage content.
typeStringNon-empty string for a public namespace or an empty string for the private namespace. For example, a beacon attachment is a public namespace.
namespaceStringMessage type. An empty string is if no type is specified when the message is created.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a policy into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
msg = Message(content: utf8.encode("Hello there!"));
msg2 = Message(content: utf8.encode("Hello there!"));
bool equals = msg.equals(msg2);
@override String toString()

Converts a message into a readable character string.

Return Type
TypeDescription
StringReadable character string of the Message object.
Call Example
Message msg = Message(
      content: utf8.encode("Hello there!"),
      type: Message.messageTypeIBeaconId,
      namespace: Message.messageNamespaceReserved);
String str = msg.toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map =
    Message(content: utf8.encode("Hello there!")).toMap();

MessageGetOption #

Obtains options for calling get.

Properties

NameTypeDescription
policyMessagePolicySubscription policy.
messagePickerMessagePickerRule for filtering messages to be received.
getCallbackMessageGetCallbackSubscription callback.

Constructor Summary

ConstructorDescription
MessageGetOption({MessagePolicy policy, MessagePicker messagePicker, MessageGetCallback getCallback})MessageGetOption constructor.

Method Summary

MethodReturn TypeDescription
toStringStringConverts a MessageGetOption object into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

MessageGetOption({MessagePolicy policy, MessagePicker messagePicker, MessageGetCallback getCallback})

Constructs a MessageGetOption instance. For parameter descriptions, see class properties.

Methods

@override String toString()

Converts a MessageGetOption object into a readable character string.

Return Type
TypeDescription
StringMessageGetOption object into a readable character string.
Call Example
String desc = MessageGetOption().toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = MessageGetOption().toMap();

MessagePutOption #

Obtains options for calling putWithOption.

Properties

NameTypeDescription
policyMessagePolicyPublish policy.
putCallbackMessagePutCallbackPublish callback.

Constructor Summary

ConstructorDescription
MessagePutOption({MessagePolicy policy, MessagePutCallback putCallback})MessagePutOption constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

MessagePutOption({MessagePolicy policy, MessagePutCallback putCallback})

Constructs a MessagePutOption instance. For parameter descriptions, see class properties.

Methods

Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = MessagePutOption().toMap();

MessagePicker #

Specifies the set of messages to be received. When the sharing code is discovered, the MessagePicker must match the message. A MessagePicker is the logical OR of multiple pickers.

Properties

NameTypeDescription
includeAllMessagePickerA picker that returns all types of messages published by the app.
includeAllTypesfinal boolIndicates whether to obtain all types of information.
eddystoneUidsfinal List<UidInstance>EddystoneUid beacon information list.
iBeaconIdsfinal List<IBeaconInfo>iBeacon beacon information list.
namespaceTypesfinal List<NamespaceType>Domain name list.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a MessagePicker object into a readable character string.
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = MessagePicker.includeAll.equals(object);
@override String toString()

Converts a MessagePicker object into a readable character string.

Return Type
TypeDescription
StringReadable character string of the MessagePicker object.
Call Example
String desc = MessagePicker.includeAll.toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = MessagePicker.includeAll.toMap();

MessagePickerBuilder #

A builder class for MessagePicker.

Constructor Summary

ConstructorDescription
MessagePickerBuilder()Creates an instance of MessagePickerBuilder.

Method Summary

MethodReturn TypeDescription
buildMessagePickerCreates an instance of MessagePicker.
includeAllMessagePickerBuilderPicks among all messages published by the app.
includeEddyStoneUidsMessagePickerBuilderIncludes Eddystone UIDs.
includeIBeaconIdsMessagePickerBuilderIncludes iBeacon IDs.
includeNamespaceTypeMessagePickerBuilderPicks among all messages in the specified namespace and with the specified type. A namespace can be specified only for beacon messages.
includePickerMessagePickerBuilderIncludes the previously constructed picker.

Constructors

MessagePickerBuilder()

Creates an instance of MessagePickerBuilder.

Methods

MessagePicker build()

Creates an instance of MessagePicker. You must call at least one include method before calling build().

Return Type
TypeDescription
MessagePickerAn instance of MessagePicker.
Call Example
MessagePicker picker =
      MessagePickerBuilder().includeAll().build();
MessagePickerBuilder includeAll()

Includes all messages published by the app.

Return Type
TypeDescription
MessagePickerBuilderMessagePickerBuilder object.
Call Example
MessagePickerBuilder builder = MessagePickerBuilder().includeAll();
MessagePickerBuilder includeEddyStoneUids(List<UidInstance> eddystoneUids)

Includes Eddystone UIDs.

An Eddystone message contains the following information:

  • namespace = Message.messageNamespaceReserved
  • type = Message.messageTypeEddystoneUid
Parameters
ParameterTypeDescription
eddystoneUidsList<UidInstance>List of EddystoneUid instances.
Return Type
TypeDescription
MessagePickerBuilderMessagePickerBuilder object.
Call Example
MessagePickerBuilder builder = MessagePickerBuilder().includeEddyStoneUids([
  UidInstance(uid: '123', instance: 'ins'),
  UidInstance(uid: '345', instance: 'ins')
]);
MessagePickerBuilder includeIBeaconIds(List<IBeaconInfo> iBeaconIds)

Includes iBeacon ID messages.

An iBeacon message contains the following information:

  • namespace = Message.messageNamespaceReserved
  • type = Message.messageTypeIBeaconId
Parameters
ParameterTypeDescription
eddystoneUidsList<IBeaconInfo>List of IBeacon instances.
Return Type
TypeDescription
MessagePickerBuilderMessagePickerBuilder object.
Call Example
MessagePickerBuilder builder = MessagePickerBuilder().includeIBeaconIds([
  IBeaconInfo(uuid: '123', major: 123, minor: 123),
  IBeaconInfo(uuid: '345', major: 345, minor: 345)
]);
MessagePickerBuilder includeNamespaceType(List<NamespaceType> namespaceTypes)

Picks among all messages in the specified namespace and with the specified type. A namespace can be specified only for beacon messages.

Parameters
ParameterTypeDescription
namespaceTypesList<NamespaceType>List of namespace types.
Return Type
TypeDescription
MessagePickerBuilderMessagePickerBuilder object.
Call Example
  MessagePickerBuilder builder = MessagePickerBuilder().includeNamespaceType(
      [NamespaceType('nmspace', 'type'), NamespaceType('nmspace2', 'type2')]);
MessagePickerBuilder includePicker(MessagePicker picker)

Includes the previously constructed picker.

Parameters
ParameterTypeDescription
pickerMessagePickerMessagePicker object.
Return Type
TypeDescription
MessagePickerBuilderMessagePickerBuilder object.
Call Example
MessagePicker picker = MessagePickerBuilder().includeIBeaconIds([
  IBeaconInfo(uuid: '123', major: 123, minor: 123),
  IBeaconInfo(uuid: '345', major: 345, minor: 345)
]).build();
MessagePickerBuilder builder = MessagePickerBuilder().includePicker(picker);

MessagePolicy #

Describes a set of policies for publishing or subscribing to messages.

Constants

NameTypeDescriptionValue
findingModeBroadcastintBroadcasts a sharing code for other devices to scan to discover nearby devices.1
findingModeScanintBroadcasts a sharing code and scans for other devices' sharing codes to discover nearby devices.2
findingModeDefaultintAllows messages to be transmitted over any distance.0
distanceTypeDefaultintAllows messages to be transmitted over any distance.0
distanceTypeEarshotintAllows messages to be transmitted only within the earshot. It is recommended that this policy be used together with findingModeBroadcast to reduce the device discovery delay.1
ttlSecondsDefaultintDefault TTL, in seconds.240
ttlSecondsInfiniteintIndefinite TTL, in seconds.0x7FFFFFFF
ttlSecondsMaxintMaximum TTL, in seconds.86400

Properties

NameTypeDescription
bleOnlystatic final MessagePolicyPolicy that uses only BLE to discover nearby devices.
findingModeintDiscovery mode.
distanceTypeintDistance type.
ttlSecondsintTimeout interval.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toMapMap<dynamic, dynamic> mapConverts an instance of the class into a map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = MessagePolicy.bleOnly.equals(object);
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = MessagePolicy.bleOnly.toMap();

MessagePolicyBuilder #

A builder class for MessagePolicy.

Constructor Summary

ConstructorDescription
MessagePolicyBuilder()Creates an instance of MessagePolicyBuilder.

Method Summary

MethodReturn TypeDescription
buildMessagePolicyCreates an instance of MessagePolicy.
setFindingModeMessagePolicyBuilderSets the scanning mode.
setDistanceTypeMessagePolicyBuilderFor message publishing, the published message will only be delivered to subscribing devices that are at the most specified distance. For message subscription, messages will only be delivered if the publishing device is at the most specified distance.
setTtlSecondsMessagePolicyBuilderIncludes iBeacon IDs.

Constructors

MessagePolicyBuilder()

Creates an instance of MessagePolicyBuilder.

Methods

MessagePolicy build()

Creates an instance of MessagePolicy.

Return Type
TypeDescription
MessagePolicyAn instance of MessagePolicy.
Call Example
MessagePolicy picker = MessagePolicyBuilder().build();
MessagePolicyBuilder setFindingMode(int findingMode)

Sets the scanning mode, which determines how devices detect each other.

Parameters
ParameterTypeDescription
findingModeintMode to detect devices, which is one of MessagePolicy.findingMode*.
Return Type
TypeDescription
MessagePolicyBuilderMessagePolicyBuilder object.
Call Example
MessagePolicyBuilder builder =
  MessagePolicyBuilder().setFindingMode(MessagePolicy.findingModeScan);
MessagePolicyBuilder setDistanceType(int distanceType)

Sets the distance for message subscription and publishing. For message publishing, the published message will only be delivered to subscribing devices that are at the most specified distance. For message subscription, messages will only be delivered if the publishing device is at the most specified distance.

Parameters
ParameterTypeDescription
distanceTypeintDistance type, which is one of MessagePolicy.distanceType*.
Return Type
TypeDescription
MessagePolicyBuilderMessagePolicyBuilder object.
Call Example
MessagePolicyBuilder builder = MessagePolicyBuilder()
    .setDistanceType(MessagePolicy.distanceTypeDefault);
MessagePolicyBuilder setTtlSeconds(int ttlSeconds)

Sets the TTL of a published or subscribed message. The TTL can either be ttlSecondsInfinite or a value ranging from 1 to ttlSecondsMax. If the TTL is not set, ttlSecondsDefault is used by default.

Parameters
ParameterTypeDescription
ttlSecondsintTime to live.
Return Type
TypeDescription
MessagePolicyBuilderMessagePolicyBuilder object.
Call Example
MessagePolicyBuilder builder =
    MessagePolicyBuilder().setTtlSeconds(MessagePolicy.ttlSecondsMax);

UidInstance #

Obtains EddystoneUid information.

Properties

NameTypeDescription
uidfinal String10-byte namespace of an Eddystone UID (in hexadecimal format), for example, c526dfec5403adc62585.
instancefinal String6-byte instance of an Eddystone UID (in hexadecimal format), for example, 32ddbcad1576.

Constructor Summary

ConstructorDescription
UidInstance({String uid, String instance})UidInstance constructor.
UidInstance.fromMap(Map<dynamic, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a UidInstance into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

UidInstance({String uid, String instance})

Constructs a UidInstance instance. For parameter descriptions, see class properties.

factory UidInstance.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = UidInstance(uid: 'uid').equals(object);
@override String toString()

Converts the UidInstance object into a readable character string.

Return Type
TypeDescription
StringUidInstance object into a readable character string.
Call Example
String desc = UidInstance(uid: 'uid').toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = UidInstance(uid: 'uid').toMap();

IBeaconInfo #

Obtains IBeacon information.

Properties

NameTypeDescription
uuidfinal StringUUID.
majorfinal intMajor value.
minorfinal intMinor value.

Constructor Summary

ConstructorDescription
IBeaconInfo({String uuid, int major, int minor})IBeaconInfo constructor.
IBeaconInfo.fromMap(Map<String, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a IBeaconInfo into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

IBeaconInfo({String uuid, int major, int minor})

Constructs a IBeaconInfo instance. For parameter descriptions, see class properties.

factory IBeaconInfo.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = IBeaconInfo(uuid: 'uuid').equals(object);
@override String toString()

Converts the IBeaconInfo object into a readable character string.

Return Type
TypeDescription
StringIBeaconInfo object into a readable character string.
Call Example
String desc = IBeaconInfo(uuid: 'uuid').toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = IBeaconInfo(uuid: 'uuid').toMap();

NamespaceType #

Obtains namespace information.

Properties

NameTypeDescription
namespaceStringNamespace of a message. The value cannot be empty or contain asterisks (*).
typeStringType of a message. The value cannot be empty or contain asterisks (*).

Constructor Summary

ConstructorDescription
NamespaceType(String namespace, String type)NamespaceType constructor.
NamespaceType.fromMap(Map<String, dynamic> map)Creates an instance of the class from a provided Map object.

Method Summary

MethodReturn TypeDescription
equalsboolChecks whether any other object is the same as this object.
toStringStringConverts a NamespaceType into a readable character string.
toMapMap<String, dynamic>Converts an instance of the class into a map object.

Constructors

NamespaceType(String namespace, String type)

Constructs a NamespaceType instance. For parameter descriptions, see class properties.

factory NamespaceType.fromMap(Map<dynamic, dynamic> map)

Creates an instance of the class from a provided Map object.

Methods

bool equals(object)

Checks whether any other object is the same as this object.

Parameters
ParameterTypeDescription
objectdynamicObject to be compared.
Return Type
TypeDescription
boolWhether two objects are equal.
Call Example
bool equals = NamespaceType('nmspace', 'type').equals(object);
@override String toString()

Converts the NamespaceType object into a readable character string.

Return Type
TypeDescription
StringNamespaceType object into a readable character string.
Call Example
String desc = NamespaceType('nmspace', 'type').toString();
Map<String, dynamic> toMap()

Converts an instance of the class into a map object.

Return Type
TypeDescription
Map<String, dynamic>An instance of the class converted into a map object.
Call Example
Map<String, dynamic> map = NamespaceType('nmspace', 'type').toMap();

MessageGetCallback #

A callback class for events related to message subscription.

Properties

NameTypeDescription
idintHash code.
onTimeoutOnTimeoutCustom function type, called when message subscription expires in any of the following situations: TTL ends, User stops the Nearby operation

Constructor Summary

ConstructorDescription
MessageGetCallback({OnTimeout onTimeout})MessageGetCallback constructor.

Constructors

MessageGetCallback({OnTimeout onTimeout})

Constructs a MessageGetCallback instance. For parameter descriptions, see class properties.


MessagePutCallback #

Represents the callback for events related to message publishing.

Properties

NameTypeDescription
idintHash code.
onTimeoutOnTimeoutCustom function type, called when message publishing expires in any of the following situations: TTL ends, The user stops publishing.

Constructor Summary

ConstructorDescription
MessagePutCallback({OnTimeout onTimeout})MessagePutCallback constructor.

Constructors

MessagePutCallback({OnTimeout onTimeout})

Constructs a MessagePutCallback instance. For parameter descriptions, see class properties.


MessageStatusCallback #

A callback class for MessageEngine status changes.

Properties

NameTypeDescription
idintHash code.
onPermissionChangedOnPermissionChangedCustom function type, called when a Nearby permission is assigned or revoked.

Constructor Summary

ConstructorDescription
MessageStatusCallback({OnPermissionChanged onPermissionChanged})MessageStatusCallback constructor.

Constructors

MessageStatusCallback({OnPermissionChanged onPermissionChanged})

Constructs a MessageStatusCallback instance. For parameter descriptions, see class properties.


NearbyMessageHandler #

Represents the callback for events such as signal change, distance change, message reception, and failure to receive a message.

Properties

NameTypeDescription
idintHash code.
onBleSignalChangedOnBleSignalChangedCustom function type, called when the first BLE broadcast message associated with Message or the BLE signal associated with Message changes. This callback currently supports only BLE beacon messages. It does not support getPending during subscription.
onDistanceChangedOnDistanceChangedCustom function type, called when the estimated distance to a message changes. This callback currently supports only BLE beacon messages. It does not support getPending during subscription.
onFoundOnFoundCustom function type, called when a message is detected for the first time or a message is no longer detectable (onLost).
onLostOnLostCustom function type, called when a message is no longer detectable. This callback currently suits BLE beacon messages the best. For other messages, it may not respond in a timely manner. The method is called back only once unless a message is no longer detectable.

Constructor Summary

ConstructorDescription
NearbyMessageHandler({OnBleSignalChanged onBleSignalChanged, OnDistanceChanged onDistanceChanged, OnFound onFound, OnLost onLost})NearbyMessageHandler constructor.

Constructors

NearbyMessageHandler({OnBleSignalChanged onBleSignalChanged, OnDistanceChanged onDistanceChanged, OnFound onFound, OnLost onLost})

Constructs a NearbyMessageHandler instance. For parameter descriptions, see class properties.


void OnTimeout() #

Custom function type defined for messaging timeout events.


void OnPermissionChanged(bool granted) #

Custom function type defined for Message engine permission changes.

Parameters

ParameterTypeDescription
grantedboolIndicates whether a permission is granted.

void OnBleSignalChanged(Message message, BleSignal signal) #

Custom function type defined for message handler OnBleSignalChanged events.

Parameters

ParameterTypeDescription
messageMessageMessage.
signalBleSignalNew BLE signal.

void OnDistanceChanged(Message message, Distance distance) #

Custom function type defined for message handler OnDistanceChanged events.

Parameters

ParameterTypeDescription
messageMessageMessage.
distanceDistanceUpdated estimated distance.

void OnFound(Message message) #

Custom function type defined for message handler OnFound events.

Parameters

ParameterTypeDescription
messageMessageMessage.

void OnLost(Message message) #

Custom function type defined for message handler OnLost events.

Parameters

ParameterTypeDescription
messageMessageMessage.

NearbyPermissionHandler #

Contains the methods for the permissions required by the Nearby Service.

Method Summary

MethodReturn TypeDescription
requestPermissionFuture<void>Requests the specified permissions.
hasLocationPermissionFuture<bool>Checks whether the application has location permission.
hasExternalStoragePermissionFuture<bool>Checks whether the application has external storage read/write permission.

Methods

Future<bool> requestPermission(List

Requests the specified permissions.

Parameters
ParameterTypeDescription
permissionsList<NearbyPermission>List of permissions.
Return Type
TypeDescription
Future<bool>Whether the all the permissions are granted. Will return false if one is rejected.
Call Example
await NearbyPermissionHandler.requestPermission(
        [NearbyPermission.location, NearbyPermission.externalStorage]);
Future<bool> hasLocationPermission()

Checks whether the application has location permission.

Return Type
TypeDescription
Future<bool>Whether the application has location permission.
Future<bool> hasExternalStoragePermission()

Checks whether the application has external storage read/write permission.

Return Type
TypeDescription
Future<bool>Whether the application has external storage read/write permission.

NearbyPermission #

Enumerated object that represents the permissions that are required and used by the plugin.

Enum Values

ValuesDescription
locationACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION
externalStorageREAD_EXTERNAL_STORAGE & WRITE_EXTERNAL_STORAGE

You can read more about the Nearby Service and its APIs from Huawei Developers


4. Configuration and Description #

Preparing for Release #

Before building a release version of your app you may need to customize the proguard-rules.pro obfuscation configuration file to prevent the HMS Core SDK from being obfuscated. Add the configurations below to exclude the HMS Core SDK from obfuscation. For more information on this topic refer to this Android developer guide.

<flutter_project>/android/app/proguard-rules.pro

-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
 
## Flutter wrapper
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.**  { *; }
-keep class io.flutter.util.**  { *; }
-keep class io.flutter.view.**  { *; }
-keep class io.flutter.**  { *; }
-keep class io.flutter.plugins.**  { *; }
-dontwarn io.flutter.embedding.**
-keep class com.huawei.hms.flutter.** { *; }
-repackageclasses

<flutter_project>/android/app/build.gradle

buildTypes {
    debug {
        signingConfig signingConfigs.config
    }
    release {
        signingConfig signingConfigs.config
        // Enables code shrinking, obfuscation and optimization for release builds
        minifyEnabled true
        // Unused resources will be removed, resources defined in the res/raw/keep.xml will be kept.
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

5. Sample Project #

This plugin includes a demo project in the example folder, there you can find more usage examples.

6. Questions or Issues #

If you have questions about how to use HMS samples, try the following options:

  • Stack Overflow is the best place for any programming questions. Be sure to tag your question with huawei-mobile-services.
  • Github is the official repository for these plugins, You can open an issue or submit your ideas.
  • Huawei Developer Forum HMS Core Module is great for general questions, or seeking recommendations and opinions.
  • Huawei Developer Docs is place to official documentation for all HMS Core Kits, you can find detailed documentations in there.

If you run into a bug in our samples, please submit an issue to the GitHub repository.

7. Licensing and Terms #

Huawei Nearby Service Flutter Plugin is licensed under Apache 2.0 license

0
likes
70
pub points
0%
popularity

Publisher

developer.huawei.com

Nearby Service Data Communication allows apps to easily discover nearby devices and set up communication with them using technologies such as Bluetooth and Wi-Fi.

Homepage
Repository (GitHub)
View/report issues

Documentation

API reference

License

Apache 2.0 (LICENSE)

Dependencies

flutter

More

Packages that depend on huawei_nearbyservice