Android实现启用GPRS/3G网络

如果要用android程序来实现wifi的开启和关闭,是一件十分简单的事,使用WifiManager就可以实现对android wifi接口的控制,开启和关闭wifi都是仅需要两行代码。但如果你想通过代码来实现对gsm、gprs或者3G等移动网络接口控制的话,则不是那么容易了,因为在android开发者文档里并没有明确的方法来实现的,通过查看android的源代码可以知道,源代码是通过ConnectivityManager.setMobileDataEnabled方法来实现移动网络中的使用数据包选项的启用和禁用的,不过android官方刻意地把这个方法隐藏了 ,是通过把方法定义为private类型来对外禁用的,也就是说只有系统级的应用才能调用setMobileDataEnabled方法来控制无线和网络中的移动网络接口。

只要巧用java中的反射就可以实现调用到ConnectivityManager类中的setMobileDataEnabled方法,从而实现用程序来启用和禁用移动网络中的使用数据包选项,达到开启和关闭gprs或者3g移动网络的目的。


接下来直接粘代码吧:

01 private void setMobileDataEnabled(Context context, booleanenabled) {
02 final String TAG = "setMobileDataEnabled";
03 final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
04 Class conmanClass;
05 try{
06 conmanClass = Class.forName(conman.getClass().getName());
07 final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
08 iConnectivityManagerField.setAccessible(true);
09 final Object iConnectivityManager = iConnectivityManagerField.get(conman);
10 final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
11 final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
12 setMobileDataEnabledMethod.setAccessible(true);
13
14 setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
15 } catch(ClassNotFoundException e) {
16 // TODO Auto-generated catch block
17 Log.d(TAG, "ClassNotFoundException");
18 } catch(NoSuchFieldException e) {
19 Log.d(TAG, "NoSuchFieldException");
20 } catch(IllegalArgumentException e) {
21 Log.d(TAG, "IllegalArgumentException");
22 } catch(IllegalAccessException e) {
23 Log.d(TAG, "IllegalAccessException");
24 } catch(NoSuchMethodException e) {
25 Log.d(TAG, "NoSuchMethodException");
26 } catch(InvocationTargetException e) {
27 Log.d(TAG, "InvocationTargetException");
28 }finally{
29
30 }
31
32 }


你可能感兴趣的:(android,网络)