目录

Querying NearLink Status

Use Cases

Before using NearLink, you need to manually enable the NearLink service in the device settings. You can obtain the NearLink status either by querying or subscribing, and start the service processes when the status changes to STATE_ON.

API Description

You can obtain the NearLink status through proactive queries or subscription notifications.

API Description
getState(): NearlinkState Obtains the NearLink status through proactive queries.
on(type: 'stateChange', callback: Callback<NearlinkState>): void Subscribes to the NearLink status change event. This API uses a callback to return the result asynchronously.
off(type: 'stateChange', callback?: Callback<NearlinkState>): void Unsubscribes from the NearLink status change event. This API uses a callback to return the result asynchronously.

Development Procedure

Turning on or off NearLink under Settings > More connectivity options > NearLink on a device (or Settings > NearLink & Bluetooth > NearLink for different products or OS versions) will trigger NearLink status changes.

  1. Import required modules.

    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { manager } from '@kit.NearLinkKit';
  2. Query the NearLink status.

    try {
      let state: manager.NearlinkState = manager.getState();
      hilog.info(this.domainId, this.logTag, `NearLink state: ${JSON.stringify(state)}`);
      // ...
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  3. Alternatively, subscribe to NearLink status changes by registering a callback.

    let onReceiveEvent: (data: manager.NearlinkState) => void = (data: manager.NearlinkState) => {
      hilog.info(this.domainId, this.logTag, `NearLink state changed: ${JSON.stringify(data)}`);
      // ...
    };
    try {
      manager.on('stateChange', onReceiveEvent);
      hilog.info(this.domainId, this.logTag, `Subscribed to stateChange`);
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }
  4. Unsubscribe from NearLink status changes. onReceiveEvent is the callback defined in Step 3.

    try {
      manager.off('stateChange');
      hilog.info(this.domainId, this.logTag, `Unsubscribed from stateChange`);
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `errCode: ${(err as BusinessError).code}, errMessage: ${(err as BusinessError).message}`);
    }