且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否移动网络启用/禁用

更新时间:2023-11-28 10:06:46

我终于找到了解决办法。显然,并不是所有的手机都有这个选项:

I finally found a solution. Apparently not all phones have this option:

首页>菜单>设置>无线和网络>移动网络(复选框)

Home > Menu > Settings > Wireless & networks > Mobile network (checkbox)

然而,对于那些谁做的,这种方法将工作:

However, for those who do, this method will work:

/**
 * @return null if unconfirmed
 */
public Boolean isMobileDataEnabled(){
    Object connectivityService = getSystemService(CONNECTIVITY_SERVICE); 
    ConnectivityManager cm = (ConnectivityManager) connectivityService;

    try {
        Class<?> c = Class.forName(cm.getClass().getName());
        Method m = c.getDeclaredMethod("getMobileDataEnabled");
        m.setAccessible(true);
        return (Boolean)m.invoke(cm);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}