我有一個PreferenceActivity,其中有一個CheckboxPreference
。我想點擊CheckboxPreference啓用或禁用移動數據,所以我編寫了這個代碼。使用CheckBoxPreference禁用或啓用移動數據?
//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;
}
});
問題,如代碼中的註釋中所述,是在調用方法時放入括號中的內容。我很抱歉如果這個問題看起來微不足道,但請耐心等待。我是初學者。
http://stackoverflow.com/questions/11662978/how-to-provide-option-to-select-wi-fi-or-gprs-for-network-connectivity-in -androi/11663173#11663173 – JiTHiN
將啓用/禁用移動數據的代碼放入方法中,並在'onPreferenceClick'方法中調用該方法。 – Sajmon
你好,謝謝你的回覆。我已經更新了我的問題,我試圖按照建議做,但我有一個問題。我能幫我嗎?提前致謝。 –