控制数据链接的开关首先要申请权限:
由于安卓没有提供公开的api进行操作,所以要使用反射才可以完成:
-
private void setMobileDataEnabled(Context context, boolean enabled) {
-
final ConnectivityManager conman = (ConnectivityManager) context
-
.getSystemService(Context.CONNECTIVITY_SERVICE);
-
Class conmanClass;
-
try {
-
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, enabled);
-
} catch (ClassNotFoundException e) {
-
Logger.e(TAG, e);
-
} catch (SecurityException e) {
-
Logger.e(TAG, e);
-
} catch (NoSuchFieldException e) {
-
Logger.e(TAG, e);
-
} catch (IllegalArgumentException e) {
-
Logger.e(TAG, e);
-
} catch (IllegalAccessException e) {
-
Logger.e(TAG, e);
-
} catch (NoSuchMethodException e) {
-
Logger.e(TAG, e);
-
} catch (InvocationTargetException e) {
-
Logger.e(TAG, e);
-
}
-
}
控制wifi则需要申请权限:
然后调用如下方法:
-
public void setWifi(boolean isEnable) {
-
if (mWm == null) {
-
mWm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
-
}
-
if (isEnable) {
-
if (!mWm.isWifiEnabled()) {
-
mWm.setWifiEnabled(true);
-
}
-
} else {
-
if (mWm.isWifiEnabled()) {
-
mWm.setWifiEnabled(false);
-
}
-
}
-
}
阅读(2549) | 评论(0) | 转发(0) |