我正在尝试通过代码将网络首选项从3G切换到2G / EDGE,反之亦然。我可以打开和关闭移动数据连接。现在我需要知道如何通过代码在3G和2G / EDGE之间切换。有人能帮我吗?提前致谢。
我正在尝试通过代码将网络首选项从3G切换到2G / EDGE,反之亦然。我可以打开和关闭移动数据连接。现在我需要知道如何通过代码在3G和2G / EDGE之间切换。有人能帮我吗?提前致谢。
其中许多代码是从/受到ChuongPham的答案启发借用的。
首先,我们需要获取ITelephony类的一个声明字段的值来获取正确的事务代码。由于我怀疑字段的名称可能因平台而异(对于我的,字段名称为“TRANSACTION_setPreferredNetworkType_96”),因此我提供了一种尽可能灵活的解决方案:
private static String get3gTransactionCode(Context context) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
final TelephonyManager mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final Class<?> mTelephonyClass = Class.forName(mTelephonyManager.getClass().getName());
final Method mTelephonyMethod = mTelephonyClass.getDeclaredMethod("getITelephony");
mTelephonyMethod.setAccessible(true);
final Object mTelephonyStub = mTelephonyMethod.invoke(mTelephonyManager);
final Class<?> mTelephonyStubClass = Class.forName(mTelephonyStub.getClass().getName());
final Class<?> mClass = mTelephonyStubClass.getDeclaringClass();
for (Field f:mClass.getDeclaredFields()) {
if (f.getName().contains("setPreferredNetworkType")) {
final Field field = mClass.getDeclaredField(f.getName());
field.setAccessible(true);
return String.valueOf(field.getInt(null));
}
}
throw new NoSuchFieldException();
}
接下来我们可以通过su在系统调用中使用事务码:
private static void setPreferredNetworkType(Context context, int preferredType) throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException {
String transactionCode = get3gTransactionCode(context);
String command = "service call phone " + transactionCode + " i32 " + preferredType;
executeCommandViaSu(context, "-c", command);
}
private static void executeCommandViaSu(Context context, String option, String command) {
boolean success = false;
String su = "su";
for (int i=0; i < 3; i++) {
// Default "su" command executed successfully, then quit.
if (success) {
break;
}
// Else, execute other "su" commands.
if (i == 1) {
su = "/system/xbin/su";
} else if (i == 2) {
su = "/system/bin/su";
}
try {
// Execute command as "su".
Runtime.getRuntime().exec(new String[]{su, option, command});
} catch (IOException e) {
success = false;
// Oops! Cannot execute `su` for some reason.
// Log error here.
} finally {
success = true;
}
}
}
Log.i("数据开关 : ", "关闭数据连接 "); dataMtd.invoke(mgr, false); }else if (!connectionStatus){ Log.i("数据开关 : ", "打开数据连接 "); dataMtd.invoke(mgr, true); } - senthil prabhu