代码控制android手机的网络开关。

1.通过代码控制wifi的开关

WifiManager wifiManager = PhoneManager.getWifiManager(context);

wifiManager.setWifiEnabled(true);//开启wifi

wifiManager.setWifiEnabled(false);//关闭wifi


2.通过代码控制手机流量的开关

输入参数

Context context;

boolean enabled;//true代表开,false代表关

需要权限:

  <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

/**
	 * 开启关闭手机网络
	 * @param context
	 * @param enabled
	 */
	private void toggleMobileData(Context context, boolean enabled) {  
	    ConnectivityManager connectivityManager = 
	    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    
	    //ConnectivityManager类  
	    Class<?> connectivityManagerClass = null;
	    //ConnectivityManager类中的字段  
	    Field connectivityManagerField = null;
	    
	    
	    //IConnectivityManager接口
	    Class<?> iConnectivityManagerClass = null;
	    //IConnectivityManager接口的对象
	    Object iConnectivityManagerObject = null;
	    //IConnectivityManager接口的对象的方法
	    Method setMobileDataEnabledMethod = null;
	    
		try {
			//取得ConnectivityManager类
			connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
			//取得ConnectivityManager类中的字段mService
			connectivityManagerField = connectivityManagerClass.getDeclaredField("mService");
			//取消访问私有字段的合法性检查 
			//该方法来自java.lang.reflect.AccessibleObject
			connectivityManagerField.setAccessible(true);
			
			//实例化mService
			//该get()方法来自java.lang.reflect.Field
			//一定要注意该get()方法的参数:
			//它是mService所属类的对象
			//完整例子请参见:
			//http://blog.csdn.net/lfdfhl/article/details/13509839
			iConnectivityManagerObject = connectivityManagerField.get(connectivityManager);
			//得到mService所属接口的Class
			iConnectivityManagerClass = Class.forName(iConnectivityManagerObject.getClass().getName());
			//取得IConnectivityManager接口中的setMobileDataEnabled(boolean)方法
			//该方法来自java.lang.Class.getDeclaredMethod
			setMobileDataEnabledMethod = 
			iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
			//取消访问私有方法的合法性检查 
			//该方法来自java.lang.reflect.AccessibleObject
			setMobileDataEnabledMethod.setAccessible(true);
			//调用setMobileDataEnabled方法
			setMobileDataEnabledMethod.invoke(iConnectivityManagerObject,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();  
		} 
	}


你可能感兴趣的:(代码控制android手机的网络开关。)