NativeScript Core

Connectivity

Obtaining connectivity information requires the tns-core-modules/connectivity module. This module contains connectivity utility methods for observing the connection type and availability.

Basics

To control and monitor the Internet connectivity , you could use the tns-core-modules/connectivity module.

const connectivityModule = require("tns-core-modules/connectivity");

Using the connectivity module with getConnectionType method, we can get the current Internet connection type.

// result is ConnectionType enumeration (none, wifi or mobile)
const connectionType = connectivityModule.getConnectionType();

switch (connectionType) {
    case connectivityModule.connectionType.none:
        // Denotes no Internet connection.
        console.log("No connection");
        break;
    case connectivityModule.connectionType.wifi:
        // Denotes a WiFi connection.
        console.log("WiFi connection");
        break;
    case connectivityModule.connectionType.mobile:
        // Denotes a mobile connection, i.e. cellular network or WAN.
        console.log("Mobile connection");
        break;
    default:
        break;
}

Android specifics: On ANdroid to access any connection related information we will need explicit permission from the user. To enable the permission request add the follwing in app/App_Resources/Android/AndroidManifest/xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Monitoring connection type is achieved through startMonitoring method.

connectivityModule.startMonitoring((newConnectionType) => {
    switch (newConnectionType) {
        case connectivityModule.connectionType.none:
            console.log("Connection type changed to none.");
            break;
        case connectivityModule.connectionType.wifi:
            console.log("Connection type changed to WiFi.");
            break;
        case connectivityModule.connectionType.mobile:
            console.log("Connection type changed to mobile.");
            break;
        default:
            break;
    }
});

// Explicitly stopping the monitoring
connectivityModule.stopMonitoring();

Improve this document

Demo Source


API Reference for the Connectivity Module