HarmonyOS 如何判断系统nfc的开关状态?

如题:HarmonyOS 如何判断系统nfc的开关状态?

阅读 699
1 个回答

可以查询当前NFC状态,以及监听NFC状态变化

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-nfccontroller-0000001813576588\#ZH-CN\_TOPIC\_0000001813576588\_\_nfcstate

测试验证controller.isNfcOpen()返回值正确的,demo如下:

import controller from '@ohos.nfc.controller'

@Entry
@Component
struct TestNetConnectionPage {

  @State monitorNfcState: string = '';
  @State queryNfcState: string = '';
  @State isNfcOpen: boolean = false;

  aboutToAppear(): void {

    if (canIUse("SystemCapability.Communication.NFC.Core")) {
      controller.on("nfcStateChange", state => {
        this.monitorNfcState = state.toString();
      });
    }
  }

  build() {
    Row() {
      Column() {

        Row() {
          Text('监听NFC状态:').width('50%');
          Text(this.monitorNfcState).width('50%');
        }.alignSelf(ItemAlign.Start);

        if (canIUse("SystemCapability.Communication.NFC.Core")) {
          Row() {
            Button('查询NFC状态:').width('50%').onClick(() => {
              this.queryNfcState = controller.getNfcState().toString();
            });
            Text(this.queryNfcState).width('50%');
          }.alignSelf(ItemAlign.Start);
        }

        if (canIUse("SystemCapability.Communication.NFC.Core")) {
          Row() {
            Button('查询NFC开关:').width('50%').onClick(() => {
              this.isNfcOpen = controller.isNfcOpen();
            });
            Text(this.isNfcOpen + '').width('50%');
          }.alignSelf(ItemAlign.Start);
        }
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进