你可以試試this,它適用於KitKat。
public boolean invokeMethod(String methodName, Object[] args) throws Exception {
ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Class ownerClass = mcm.getClass();
Class[] argsClass = null;
if (args != null) {
argsClass = new Class[1];
argsClass[0] = args.getClass();
}
Method method = ownerClass.getMethod(methodName, argsClass);
return (Boolean)method.invoke(mcm, args);
}
public Object invokeBooleanArgMethod(String methodName, boolean value) throws Exception {
ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Class ownerClass = mcm.getClass();
Class[] argsClass = new Class[1];
argsClass[0] = boolean.class;
Method method = ownerClass.getMethod(methodName,argsClass);
return method.invoke(mcm, value);
}
/* use these two method like these */
Object[] arg = null;
try {
boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled", arg);
if(!isMobileDataEnable){
invokeBooleanArgMethod("setMobileDataEnabled", true);
}
} catch (Exception e) {
e.printStackTrace();
}
此外,在AndroidManifest.xml
,你需要添加
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
如果您有任何其他想法,我又怎麼能對移動數據的切換按鈕爲2.3+版本,請告訴我... –