標籤:
在項目的開發中因為要使用到WIFI和GPRS網路的切換,因此就研究了一下通過代碼開啟WIFI和GPRS的工作。
無論是切換WIFI還是切換GPRS網路都需要設定相應的許可權,所以需要在AndroidManifest.xml檔案中加入以下幾行代碼。
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
1、切換WIFI網路
public static void toggleWiFi(Context context, boolean enabled) {WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);wm.setWifiEnabled(enabled);}
2、切換GPRS網路
由於Android沒有提供直接切換GPRS網路的方法,通過查看系統源碼發現,系統是調用IConnectivityManager類中的setMobileDataEnabled(boolean)方法來設定GPRS網路的,由於方法不可見,只能採用反射來調用,代碼如下。
public static void toggleMobileData(Context context, boolean enabled) {ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);Class<?> conMgrClass = null; // ConnectivityManager類Field conMgrField = null; // ConnectivityManager類中的欄位Object iConMgr = null; // IConnectivityManager類的引用Class<?> iConMgrClass = null; // IConnectivityManager類Method setMobileDataEnabledMethod = null; // setMobileDataEnabled方法try {// 取得ConnectivityManager類conMgrClass = Class.forName(conMgr.getClass().getName());// 取得ConnectivityManager類中的對象mServiceconMgrField = conMgrClass.getDeclaredField("mService");// 設定mService可訪問conMgrField.setAccessible(true);// 取得mService的執行個體化類IConnectivityManageriConMgr = conMgrField.get(conMgr);// 取得IConnectivityManager類iConMgrClass = Class.forName(iConMgr.getClass().getName());// 取得IConnectivityManager類中的setMobileDataEnabled(boolean)方法setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);// 設定setMobileDataEnabled方法可訪問setMobileDataEnabledMethod.setAccessible(true);// 調用setMobileDataEnabled方法setMobileDataEnabledMethod.invoke(iConMgr, enabled);}catch (ClassNotFoundException e) {e.printStackTrace();}catch (NoSuchFieldException e) {e.printStackTrace();}catch (SecurityException e) {e.printStackTrace();}catch (NoSuchMethodException e) {e.printStackTrace();}catch (IllegalArgumentException e) {e.printStackTrace();}catch (IllegalAccessException e) {e.printStackTrace();}catch (InvocationTargetException e) {e.printStackTrace();}}
根據以上所寫就可以做到WIFI網路和GPRS網路的切換了。
Android開發中WIFI和GPRS網路的切換