How to check internet access (INCLUDING tethering!

2019-09-11 08:04发布

I am looking for a piece of code that would check network connectivity, of an Android device, including tethering, not only the wireless channels.

I have spent hours online looking for such a thing, but without any result! All the functions I found out manage only wireless net tests. Nothing with tethering. So is it at least possible? Do you have some corresponding?

2条回答
Animai°情兽
2楼-- · 2019-09-11 08:10

this checks if Tethering is enabled. Cut from a class I changed to get adbWireless working over a tethered connection:

    // check if tethering is on
    try {
        Method[] wmMethods = mWifiManager.getClass().getDeclaredMethods();
        for(Method method: wmMethods)
            if("isWifiApEnabled".equals(method.getName()))
                return (Boolean) method.invoke(mWifiManager);
        return false;
    } catch (Exception x) {return false;}

And you also need android.permission.ACCESS_WIFI_STATE

查看更多
家丑人穷心不美
3楼-- · 2019-09-11 08:30

Check this out:

    public static boolean isOnline(Context context) {
    boolean isOnline = false;
    try {
        final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
        if(activeNetwork != null && activeNetwork.isConnected() && activeNetwork.isAvailable()) {
            isOnline = true;
        } else {
            isOnline = false;
        } 
    } catch(Exception e) {
        Log.e(Config.LOG_TAG, e.toString());
        isOnline = false;
    }
    return isOnline;
}

Also add such permission into AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
查看更多
登录 后发表回答