I have a PreferenceActivity in which there is a CheckboxPreference
. I would like clicking on CheckboxPreference enable or disable Mobile Data, so I wrote this code.
//Outside of Methods
void turnData(boolean ON) throws Exception
{
final ConnectivityManager conman = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final java.lang.reflect.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);
}
//In the onCreate
final boolean o = false;
boolean mobileDataEnabled = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true);
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
}
if(mobileDataEnabled) {
((CheckBoxPreference)Data).setChecked(true);
//The Mobile Data are enabled
Data.setSummary("Mobile Data enabled");
dati = true;
}
else {
//The Mobile Data are disabled
((CheckBoxPreference)Data).setChecked(false);
try {
turnData(mobileDataEnabled);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Data.setSummary("Mobile Data disabled");
dati = false;
}
Data.setOnPreferenceClickListener( new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (dati==true) {
Data.setSummary("Mobile Data enabled");
dati = false;
}
else if (dati==false){
try {
//The problem is here
//What should I put in the parentheses?
turnData(o);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Data.setSummary("Mobile Data disabled");
dati = true;
}
return false;
}
});
The problem, as noted in the comments in the code, is what to put in the parentheses when calling the method. I apologize if the question may seem trivial **but please bear with me. I'm beginner.