Android開發中WIFI和GPRS網路的切換

來源:互聯網
上載者:User

標籤:

在項目的開發中因為要使用到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網路的切換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.