2011-11-04 119 views
5

我可以检查程序是否启用了Android设备的共享程序?有没有办法检查tethering是否活动?

我刚看了WifiManager类。 WiFiInfo中的所有vatraible都显示与设备上的WIFI关闭相同的值。

Thnaks, 问候

+0

网络共享功能位于Conne ctivityManager类,但隐藏,不在公共API中。如果您打算使用“未发布的API”,则需要修改框架JAR或使用反射。你正在寻找的方法可能是String [] ConnectivityManager#getTetheredIfaces(),它返回当前连接的网络接口。 – Jens

回答

7

使用反射尝试,就像这样:

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(); 
} 
} 

(它返回一个Boolean


丹尼斯认为这是更好地使用:

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

(经理是WiFiManager

+0

非常感谢! – softwaresupply

+0

无需迭代所有已声明的方法:Class类具有“getDeclaredMethod”方法。查看我答案中的代码。 –

5

首先,你需要获得WifiManager:

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

然后:

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; 
} 

而且你需要在AndroidManifest.xml请求权限:

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

所有决赛的目的是什么?这些在某些情况下是否需要? – diedthreetimes

+0

@diedthreetimes:“所有决赛的目的是什么?在某些情况下需要这些吗?” - 编码风格,每个都是他们自己的。请参见[我应该使用final](https://programmers.stackexchange.com/q/48413/158721)和[最终滥用](https://programmers.stackexchange.com/q/98691/158721)。 – Daniel

+0

有一点补充:应该检查“getSystemService”是否返回null。 –

相关问题