使用Froyo 2.2上的代码启用/禁用移动数据(GPRS)

时间:2013-05-10 17:43:05

标签: android android-2.2-froyo 3g-network

我正在尝试启用/禁用移动数据连接。 我已经通过 rIHaN JiTHiN Enable/Disable Mobile Data (GPRS) using code)使用了这个代码,它在Android 4.0上完美运行,但它不在我的Galaxy S(Froyo 2.2)上......

有没有办法以编程方式启用/禁用数据连接?

如果有人知道为什么它不适用于Froyo,那将非常有帮助。根据 rIHaN JiTHiN ,此代码适用于所有Android版本......

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码

检查是启用还是禁用
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (mMobile.isConnected()) {
    //if internet connected
}

如果已停用,您可以使用此

froyo设备上启用它
void turnData(boolean ON) throws Exception
{

if(bv == Build.VERSION_CODES.FROYO)
{

    Log.i("version:", "Found Froyo");
    try{ 
        Method dataConnSwitchmethod;
        Class telephonyManagerClass;
        Object ITelephonyStub;
        Class ITelephonyClass;
        TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);

        telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
    Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
    getITelephonyMethod.setAccessible(true);
    ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
    ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());

    if (ON) {
         dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("enableDataConnectivity"); 

    } else {
        dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("disableDataConnectivity");
    }
    dataConnSwitchmethod.setAccessible(true);
    dataConnSwitchmethod.invoke(ITelephonyStub);
    }catch(Exception e){
          Log.e("Error:",e.toString());
    }

}
 else
{
   Log.i("version:", "Found Gingerbread+");
   final ConnectivityManager conman = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
   final Class conmanClass = Class.forName(conman.getClass().getName());
   final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
   iConnectivityManagerField.setAccessible(true);
   final Object iConnectivityManager = iConnectivityManagerField.get(conman);
   final Class iConnectivityManagerClass =  Class.forName(iConnectivityManager.getClass().getName());
   final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
   setMobileDataEnabledMethod.setAccessible(true);
   setMobileDataEnabledMethod.invoke(iConnectivityManager, ON);
}

也不要忘记将这些内容添加到manifest

android.permission.UPDATE_DEVICE_STATS
android.permission.CHANGE_NETWORK_STATE
android.permission.ACCESS_NETWORK_STATE
android.permission.MODIFY_PHONE_STATE
android.permission.READ_PHONE_STATE