问题
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