Is there a way to check whether tethering is active?

孤人 提交于 2019-12-18 16:55:16

问题


can I check programmaticall wheter the android device has tethering activated?

I just watched the WifiManager class. All vatraibles from the WifiInfo show the same values as iff the WIFI is turned off on the device.

Thnaks, best regards


回答1:


Try using reflection, like so:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method[] wmMethods = wifi.getClass().getDeclaredMethods();
for(Method method: wmMethods){
if(method.getName().equals("isWifiApEnabled")) {

try {
  method.invoke(wifi);
} catch (IllegalArgumentException e) {
  e.printStackTrace();
} catch (IllegalAccessException e) {
  e.printStackTrace();
} catch (InvocationTargetException e) {
  e.printStackTrace();
}
}

(It returns a Boolean)


As Dennis suggested it is better to use this :

    final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
    method.setAccessible(true); //in the case of visibility change in future APIs
    return (Boolean) method.invoke(manager);

(manager is the WiFiManager)




回答2:


First, you need to get WifiManager:

Context context = ...
final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

Then:

public static boolean isSharingWiFi(final WifiManager manager)
{
    try
    {
        final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
        method.setAccessible(true); //in the case of visibility change in future APIs
        return (Boolean) method.invoke(manager);
    }
    catch (final Throwable ignored)
    {
    }

    return false;
}

Also you need to request a permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>


来源:https://stackoverflow.com/questions/8007361/is-there-a-way-to-check-whether-tethering-is-active

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