【Lesson5】在qml中检测网络状态变化


  • 船长

    代码来自 harbour-sailfinder

    利用qml的dbus接口连接net.connman,获取状态。
    简单的demo如下

    import QtQuick 2.0
    import Sailfish.Silica 1.0
    import Nemo.DBus 2.0
    
    Page{
    
        property bool networkStatus
    
        onNetworkStatusChanged: {
            if(networkStatus == false) {
                // Network connection failure
                // Do some thing
            }
        }
    
    
        // from https://github.com/DylanVanAssche/harbour-sailfinder/blob/develop/qml/harbour-sailfinder.qml
        DBusInterface {
            bus: DBus.SystemBus
            service: "net.connman"
            path: "/"
            iface: "net.connman.Manager"
            signalsEnabled: true
            Component.onCompleted: getStatus() // Init
    
            // Methods
            function getStatus() {
                typedCall("GetProperties", [], function(properties) {
                    if(properties["State"] == "online") {
                        networkStatus = true
                    }
                    else {
                        networkStatus = false
                    }
                },
                function(trace) {
                    console.error("Network state couldn't be retrieved: " + trace)
                })
            }
    
            // Signals
            function propertyChanged(name, value) {
                if(name == "State") {
                    if(value == "online") {
                        networkStatus = true
                    }
                    else {
                        networkStatus = false
                    }
                }
            }
        }
        
    }
    

登录后回复