Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

android - How to check if mobile network is enabled/disabled

I would like to know if the mobile network is enabled or disabled.

My application is designed to help the user when he receives a phone call, and to do this I need Internet access. Thus, I would like to display an information box when the user access the application for the first time if Wi-Fi has a sleep policy and Mobile network is disabled. (I need Internet within milliseconds after the phone start ringing).

I found Settings.System.WIFI_SLEEP_POLICY, but I can't find any information on how to check if mobile network is disabled (when Wi-Fi is on and working).

Any help would be appreciated!

Edit: The problem is that I want to know if mobile network is turned of by the user (while the phone could have WiFi access at the time).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...