开发者

Ping to check for connectivity to a domain

开发者 https://www.devze.com 2023-03-19 16:52 出处:网络
In my android application I am querying a database. I am only able to query the database if the phone is开发者_开发百科 connected to the internal network, i.e: by being connected to company WiFi, or b

In my android application I am querying a database. I am only able to query the database if the phone is开发者_开发百科 connected to the internal network, i.e: by being connected to company WiFi, or by using VPN connection.

I would like to check this connection first - maybe by trying to 'ping' the server first? Is this possible?

Thanks.


Just try to connect to the network/database/ip and handle any exception thrown b/c the network is unreachable or b/c of a time out.

You can also try InetAddress which has an isReachable() method.


You could consider using android.net.ConectivityManager if you really want to check the network status.

ConectivityManager.requestRouteToHost() can be used to ensure a server is reachable (although doubts have been raised about its reliability - mentioned in CommonsWare answer here : how to mange wifi internet connectivity in android? )

Alternatively, if you just want to check WIFI is connected, try

ConectivityManager.getNetworkInfo(ConectivityManager.TYPE_WIFI).isConnected()

Couple of caveats :

1) I'm typing this in a browser not an IDE, so it might have syntax errors,

2) You'll have to make that code much more defensive for production, and

3) All connectivity tests in ConectivityManager can be unreliable if networks are currently becoming available or unavailable.

Hope this covers what you were asking.

0

精彩评论

暂无评论...
验证码 换一张
取 消