android - 更改移动网络模式(gsm、wcdma、自动)

标签 android android-networking telephony

我想更改首选网络模式,即。 gsm 或 wcdma 或自动,以编程方式,从代码,在 Android 上。

这可能吗,如果可能的话怎么办?

最佳答案

有可能,我做到了。

为此,您的应用必须使用系统 key 签名或具有运营商权限。否则应用程序将抛出 java.lang.SecurityException:没有修改权限或运营商特权。

我的应用程序在 Android 5.1 Lollipop(API 22) 上运行并使用系统 key 签名,因此这是我可以确认有效的唯一配置。我无法确认运营商特权方法。

AndroidManifest.xml

将此权限添加到您的应用 list 。如果您使用的是 Android Studio,它可能会将此行标记为错误,因为只有系统应用程序才能拥有此权限。如果您可以使用系统 key 为您的应用签名,请不要担心。

<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>

获取首选网络

返回在 RILConstants.java 中定义,例如RILConstants.NETWORK_MODE_WCDMA_PREF

public int getPreferredNetwork() {
    Method method = getHiddenMethod("getPreferredNetworkType", TelephonyManager.class, null);
    int preferredNetwork = -1000;
    try {
        preferredNetwork = (int) method.invoke(mTelephonyManager);
        Log.i(TAG, "Preferred Network is ::: " + preferredNetwork);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    return preferredNetwork;
}

设置首选方法。

参数必须基于RILConstants.java,例如:RILConstants.NETWORK_MODE_LTE_ONLY

public void setPreferredNetwork(int networkType) {
    try {
        Method setPreferredNetwork = getHiddenMethod("setPreferredNetworkType",
                TelephonyManager.class, new Class[] {int.class});
        Boolean success = (Boolean)setPreferredNetwork.invoke(mTelephonyManager,
                networkType);
        Log.i(TAG, "Could set Network Type ::: " + (success.booleanValue() ? "YES" : "NO"));
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

这是一个访问隐藏 API 方法的实用方法。

/**
 * Get a hidden method instance from a class
 * @param methodName The name of the method to be taken from the class
 * @param fromClass The name of the class that has the method
 * @return A Method instance that can be invoked
 */
public Method getHiddenMethod(String methodName, Class fromClass, Class[] params) {
    Method method = null;
    try {
        Class clazz = Class.forName(fromClass.getName());
        method = clazz.getMethod(methodName, params);
        method.setAccessible(true);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return method;
}

关于android - 更改移动网络模式(gsm、wcdma、自动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10170179/

相关文章:

android - IndexedDB 在应用程序安装后自动恢复

java - 确定网络类型是 2G、3G 还是 4G

sockets - 在 Android 中我应该选择 Boost Asio 还是 Async Socket 线程?

android - 如何以编程方式更改电话类型?

android - 以编程方式检查 PIN 锁定是否在 Android 中处于 Activity 状态

javascript - Amazon Connect 出站 CCP 软电话号码预填

android - 不断检查 Android 服务中的音量变化

javascript - 开发离线 MathJax Android 移动应用程序

android - 更新回收器 View 来自不同 Activity 的项目

android - Android 中的上传和下载速率分析