欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android實(shí)現(xiàn)WIFI和GPRS網(wǎng)絡(luò)的切換

 更新時(shí)間:2019年11月04日 14:49:11   作者:^_^laoz^_^  
這篇文章主要介紹了Android實(shí)現(xiàn)WIFI和GPRS網(wǎng)絡(luò)的切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

在項(xiàng)目的開發(fā)中因?yàn)橐褂玫絎IFI和GPRS網(wǎng)絡(luò)的切換,因此就研究了一下通過代碼打開WIFI和GPRS的工作。

無論是切換WIFI還是切換GPRS網(wǎng)絡(luò)都需要設(shè)置相應(yīng)的權(quán)限,所以需要在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網(wǎng)絡(luò)

public static void toggleWiFi(Context context, boolean enabled) {
 WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
 wm.setWifiEnabled(enabled);
 }

2、切換GPRS網(wǎng)絡(luò)

由于Android沒有提供直接切換GPRS網(wǎng)絡(luò)的方法,通過查看系統(tǒng)源碼發(fā)現(xiàn),系統(tǒng)是調(diào)用IConnectivityManager類中的setMobileDataEnabled(boolean)方法來設(shè)置GPRS網(wǎng)絡(luò)的,由于方法不可見,只能采用反射來調(diào)用,代碼如下。

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類中的對象mService
 conMgrField = conMgrClass.getDeclaredField("mService");
 // 設(shè)置mService可訪問
 conMgrField.setAccessible(true);
 // 取得mService的實(shí)例化類IConnectivityManager
 iConMgr = conMgrField.get(conMgr);
 // 取得IConnectivityManager類
 iConMgrClass = Class.forName(iConMgr.getClass().getName());
 // 取得IConnectivityManager類中的setMobileDataEnabled(boolean)方法
 setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
 // 設(shè)置setMobileDataEnabled方法可訪問
 setMobileDataEnabledMethod.setAccessible(true);
 // 調(diào)用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();
 }
 }

根據(jù)以上所寫就可以做到WIFI網(wǎng)絡(luò)和GPRS網(wǎng)絡(luò)的切換了。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論