Android 5.0以上移动网络开关

Android 5.0以前使用ConnectivityManager通过反射两个方法setMobileDataEnabled和getMobileDataEnabled来控制移动网络开和关。
Android 5.0以后使用TelephonyMananger类通过反射获取setDataEnabled和getDataEnabled类完成操作。
注意:需要使用系统权限:android:sharedUserId=”android.uid.system”。

public void setMobileDataState(Context context, boolean enabled) {
    TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    try {
        Method setDataEnabled = telephonyService.getClass().getDeclaredMethod("setDataEnabled",boolean.class);
        if (null != setDataEnabled) {
            setDataEnabled.invoke(telephonyService, enabled);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public boolean getMobileDataState(Context context) {
    TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    try {
        Method getDataEnabled = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
        if (null != getDataEnabled) {
            return (Boolean) getDataEnabled.invoke(telephonyService);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
1
 "android.permission.MODIFY_PHONE_STATE" />

自适应Android5.0以前及以后的代码:

TelephonyManager mTelephonyManager = (TelephonyManager)context                  .getSystemService(Context.TELEPHONY_SERVICE);
ConnectivityManager mConnectivityManager =(ConnectivityManager)context                                  .getSystemService(Context.CONNECTIVITY_SERVICE);
public void setDataEnable(){
    Object object = Build.VERSION.SDK_INT >= 21 ?       mTelephonyManager : mConnectivityManager;  
    String methodName = Build.VERSION.SDK_INT >= 21 ? "setDataEnabled" : "setMobileDataEnabled";  
    Method setMobileDataEnable;  
    try {  
        setMobileDataEnable = object.getClass().getMethod(methodName, boolean.class);  
        setMobileDataEnable.invoke(object, true);   
      } catch (Exception e) {  
            e.printStackTrace();    
      }  
}
public void checkConnectState(){
    while(true){
        Object object = Build.VERSION.SDK_INT >= 21 ? mTelephonyManager : mConnectivityManager;  
        String methodName = Build.VERSION.SDK_INT >= 21 ? "getDataEnabled" : "getMobileDataEnabled";  
         Method getMobileDataEnable;  
         boolean isDataEnabled = false;
         try {  
             getMobileDataEnable = object.getClass().getMethod(methodName, null);  
             isDataEnabled = (Boolean) getMobileDataEnable.invoke(object, null);   
            } catch (Exception e) {  
                e.printStackTrace();    
            }  
            if(isDataEnabled){
                break;
            }else{
                sleep(200);
            }
    }
}

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