2011-11-04 61 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。 –

相關問題