首页 > 解决方案 > 连接模块无法使用 Nativescript

问题描述

我遵循教程,并在 app.component.ts 中编写此代码。

    export class AppComponent implements OnInit {
    isConnection: boolean;
    constructor() {}
    ngOnInit() {
        const myConnectionType = getConnectionType();
        switch (myConnectionType) {
            case connectionType.none:
                this.isConnection= false;
                dialogs.confirm({
                    message: "Please, check Wifi",
                    okButtonText: "OK",
                }).then(result => {
                    console.log("Dialog result: " + result);
                });
                break;
            case connectionType.wifi:
                this.isConnection= true
                break;
            case connectionType.mobile:
                this.isConnection= false;
                dialogs.confirm({
                    message: "Please, check Wifi",
                    okButtonText: "OK",
                }).then(result => {
                    console.log("Dialog result: " + result);
                });
                break;
            case connectionType.ethernet:
                this.isConnection= false;
                dialogs.confirm({
                    message: "Please, check Wifi",
                    okButtonText: "OK",
                }).then(result => {
                    console.log("Dialog result: " + result);
                });
                break;
            default:
                break;
        }
    }
}

我不明白为什么我断开 WiFi 后不起作用?

在 app.component.html 中

<page-router-outlet></page-router-outlet>

在 AndroidManifest/xml 我把<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

请问你有什么想法吗?

标签: androidtypescriptnativescriptmultipeer-connectivity

解决方案


回答您的问题“为什么我断开 WiFi 时不起作用?” 我们“ You have to monitor the connection”。在您的代码中,您只是检查应用程序加载时的连接类型,但您还必须对其进行监控,以防您想要检查何时断开 wi-fi。

ngOnInit() {
connectivity.startMonitoring((newConnectionType: number) => {
      switch (newConnectionType) {
        case connectivity.connectionType.none:
          this._userService.connectionType = AppConstants.INT_CONN_NONE;
          console.log('Connection type changed to none.');
          break;
        case connectivity.connectionType.wifi:
          this._userService.connectionType = AppConstants.INT_CONN_WIFI;
          console.log('Connection type changed to WiFi.');
          break;
        case connectivity.connectionType.mobile:
          this._userService.connectionType = AppConstants.INT_CONN_MOBILE;
          console.log('Connection type changed to mobile.');
          break;
        default:
          break;
      }
    });
}

推荐阅读