Data connection enable/disable code crashes inside

2019-05-18 09:25发布

问题:

void turnData(boolean ON)
 {
   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);
}

The above code is to enable/disable Data Connection in android 2. 3+. It works without any errors when I run it in an Activity. But when i tried to run it inside a service the application crashed. Can anyone tell me why this happened?

回答1:

Problem solved by adding the following additional permissions to the Manifest file:

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