How to check internet access (INCLUDING tethering!) on Android?

你。 提交于 2020-01-07 02:33:30

问题


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?


回答1:


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




回答2:


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" />


来源:https://stackoverflow.com/questions/13474205/how-to-check-internet-access-including-tethering-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!